The Enigma of Local Classes in STL Algorithms
Despite lambda expressions being widely employed as predicates in STL algorithms, local classes seem to be mysteriously excluded from this utility. In this question, we seek to unravel the standard-mandated restriction that prohibits local types from participating in STL algorithms as predicates.
The Standard's Prohibition
The absence of local classes as predicate types within STL algorithms stems from an explicit prohibition imposed by the C 98/03 standard, as noted in the C 03 article 14.3.1:
"A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter."
This restriction manifests in compilers flagging code like the example provided, where the local struct even cannot be used as a predicate for std::remove_if.
Rationale for the Restriction
The rationale for this exclusion is shrouded in conjecture. Some speculate it was an oversight, while others believe it was intended to prevent ad-hoc and potentially confusing type definitions within algorithms.
Evolution in C 11
Fortunately, the C 11 standard rectified this issue, lifting the restriction on local types as template arguments. Consequently, contemporary compilers generally allow the use of local classes as predicates in STL algorithms.
Conclusion
While the original prohibition on local classes was a source of frustration, its removal in C 11 has opened up new avenues for utilizing local types in STL algorithms. Today, lambda expressions and local classes coexist as effective predicate options, providing developers with versatile tools for algorithm manipulation.
The above is the detailed content of Why Can\'t Local Classes Be Used as Predicates in STL Algorithms (C 98/03)?. For more information, please follow other related articles on the PHP Chinese website!