Leveraging Local Classes with STL Algorithms
While exploring the multifaceted nature of STL algorithms, you may question the inability to utilize locally defined classes as predicates within these algorithms. The origins of this restriction lie within the confines of the C 98/03 standard.
According to article 14.3.1 of the standard, limitations apply to types serving as template parameters. Among these constraints is the prohibition of local types, types devoid of linkage, unnamed types, or types derived from any combination thereof.
template <class T> class Y { /* ... */ }; void func() { struct S { /* ... */ }; //local class Y< S > y1; // error: local type used as template-argument Y< S* > y2; // error: pointer to local type used as template-argument }
This restriction, albeit unintentional, persisted due to the slow pace of standard evolution. Nonetheless, contemporary compilers, embracing the advancements of later C versions, now generally permit the use of local types within algorithms.
Example:
#include <vector> #include <algorithm> int main() { int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::vector<int> v(array, array + 10); struct even : public std::unary_function<int, bool> { bool operator()(int x) { return !(x % 2); } }; std::remove_if(v.begin(), v.end(), even()); // compiles successfully return 0; }
In the current C landscape, the use of locally defined types within STL algorithms has become a commonplace practice, along with the introduction of lambda expressions, further enhancing algorithmic flexibility.
The above is the detailed content of Can I Use Local Classes with STL Algorithms in Modern C ?. For more information, please follow other related articles on the PHP Chinese website!