Home > Backend Development > C++ > Can I Use Local Classes with STL Algorithms in Modern C ?

Can I Use Local Classes with STL Algorithms in Modern C ?

Susan Sarandon
Release: 2024-11-23 10:17:12
Original
565 people have browsed it

Can I Use Local Classes with STL Algorithms in Modern C  ?

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template