Home > Backend Development > C++ > body text

Can Local Classes Be Used as Template Arguments in STL Algorithms?

DDD
Release: 2024-11-16 10:42:02
Original
836 people have browsed it

Can Local Classes Be Used as Template Arguments in STL Algorithms?

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.
Copy after login

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() );
}
Copy after login

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!

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