Home > Backend Development > C++ > body text

Why Can\'t Local Classes Be Used as Predicates in STL Algorithms (C 98/03)?

DDD
Release: 2024-11-22 10:16:10
Original
667 people have browsed it

Why Can't Local Classes Be Used as Predicates in STL Algorithms (C  98/03)?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template