Home > Backend Development > C++ > body text

Can Local Classes Finally Be Used as Predicates for STL Algorithms in C 11?

Mary-Kate Olsen
Release: 2024-11-21 05:04:39
Original
568 people have browsed it

Can Local Classes Finally Be Used as Predicates for STL Algorithms in C  11?

Using Local Classes with STL Algorithms: Unraveling the Local Type Restriction

In the realm of C programming, local classes have long been disallowed as predicates for STL algorithms, raising questions about the underlying restriction and its rationale.

The C 98/03 standard explicitly prohibits local types as template arguments, including local classes. Article 14.3.1 of the standard unequivocally states that "local types [...] shall not be used as a template-argument for a template type-parameter."

The rationale behind this restriction stems from the ephemeral nature of local types. As they exist within a limited scope, their destructions can occur unexpectedly, potentially leading to undefined behavior when used as predicates for STL algorithms.

However, with the advent of C 11, this restriction was lifted. The revised standard allows for local types to be used as template arguments, enabling local classes to serve as predicates for STL algorithms.

For example, consider the following code snippet:

#include <algorithm>
#include <vector>

int main() {
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::vector<int> v(array, array + 10);

    struct even {
        bool operator()(int x) { return !(x % 2); }
    };
    std::remove_if(v.begin(), v.end(), even());
}
Copy after login

In this code, the local class even defines a predicate that checks for even numbers. This class can now be used directly as an argument to the std::remove_if algorithm, which removes all even numbers from the vector v.

While the restriction on local types was initially intended to safeguard against potential undefined behavior, its removal in C 11 has opened up new possibilities for using local classes in functional programming scenarios.

The above is the detailed content of Can Local Classes Finally Be Used as Predicates for STL Algorithms in C 11?. 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