Using Locally Defined Classes with STL Algorithms
In programming, it is often desirable to use locally defined classes as predicates for STL algorithms. Unfortunately, the C 98/03 standard explicitly forbids this practice, stating that:
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 is stated in Article 14.3.1 of the C standard.
Initially, this restriction was considered a mistake by many programmers and would have been fixed sooner if the standard evolved faster. However, C 11 has removed this restriction, allowing local types to be used as template arguments.
For example, the following code, which was previously invalid in C 98/03, is now allowed in C 11:
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() ); }
Most modern compilers allow the use of local classes as template arguments, along with providing support for lambda expressions.
The above is the detailed content of Can Local Classes Be Used as Template Arguments in STL Algorithms?. For more information, please follow other related articles on the PHP Chinese website!