What is a functional object?
- oneif I do not answer zhrebut in the army help! - Kolya
- Well, there is not so bad, and not so scary ;-) - Grundy
- @Grundy modesh answer? - Kolya
- 6It is very good that zagrebut! - Vladimir Martyanov
- 6@ Kolya, you might think that learning is better than not learning. And you will save this site from your questions like "I did not teach anything, but I really need X." Also, by your example, you will show the rest that learning is good. - Vladimir Martyanov
1 answer
It is interesting to note that, strictly speaking, the C ++ standard does not use the term functional object , that is, the term functional object . There is a term function object .
I do not know whether these terms are equivalent from the point of view of English grammar. :)
I will use the term function object. Simply put, this term means a class object that has a function call operator and can be used where a postfix function call expression is used.
From the standard C ++ (20.9 Function objects)
1 A function object type (3.9) a function call (5.2.2, 13.3.1.1) .231 A function object type. In the whereabouts of the interface, there is a function for the object. This function not only makes it possible.
The most well-known representative of the function object is the lambda expression.
Here is a demo program. In the first loop, the global function ::IsEven , and in the second loop, the function object is called - a local lambda expression with the same name IsEven , which has an implicit function call operator. The declaration lambda expression hides the name of a global function.
#include <iostream> bool IsEven( int x ) { return x % 2 == 0; } int main() { int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for ( int x : a ) { std::cout << x << " is " << ( IsEven( x ) ? "even" : "odd" ) << " number" << std::endl; } std::cout << std::endl; auto IsEven = []( int x ) { return x % 2 == 0; }; for ( int x : a ) { std::cout << x << " is " << ( IsEven( x ) ? "even" : "odd" ) << " number" << std::endl; } } Output to console:
0 is even number 1 is odd number 2 is even number 3 is odd number 4 is even number 5 is odd number 6 is even number 7 is odd number 8 is even number 9 is odd number 0 is even number 1 is odd number 2 is even number 3 is odd number 4 is even number 5 is odd number 6 is even number 7 is odd number 8 is even number 9 is odd number Instead of lambda expressions, you could define your own functional object. For example, you can replace the announcement in the demo program
auto IsEven = []( int x ) { return x % 2 == 0; }; on
struct { bool operator ()( int x ) const { return x % 2 == 0; } } IsEven; and the output of the program would be the same. This last declaration defines an object called IsEven nameless structure that contains the definition of the function call operator.