##definition
- Functor (functor): having an object-function properties.
- In C ++ functor name for the new function objects (function object). Functor class object like a function is called, the call functor class object, the actual call is overloaded class functor operator () function. The main purpose functor is with STL algorithms.
Application of the algorithm ## is generally defined STL two versions: one implementation frequently used functions, the default processing method. Another approach for providing generalization capability allows the user to specify criteria comparison algorithm or designated "Operation" algorithm applied to the like elements in the container. Here is a comparison criteria template parameter algorithm. Such as the two versions of the STL search algorithm provided: the default version:
template <class _ForwardIter1, class _ForwardIter2>
_ForwardIter1 search(_ForwardIter1 __first1, _ForwardIter1 __last1,
_ForwardIter2 __first2, _ForwardIter2 __last2)
Specifies the version of the comparative method:
template <class _ForwardIter1, class _ForwardIter2, class _BinaryPred>
_ForwardIter1 search(_ForwardIter1 __first1, _ForwardIter1 __last1,
_ForwardIter2 __first2, _ForwardIter2 __last2,
_BinaryPred __predicate)
You can see, the template parameter specifies the version of the comparative method in more than a predicate template _BinaryPred, for comparison criteria specified element. And the default version uses = operator determines whether or not equal.
There are many ways to specify operation:
- Generally it is, and passed to the function pointer as a parameter to the algorithm defined by the function.
- Class may also be defined, and in the class overloaded operator () function, such as a class functor class.
- Lambda use an anonymous function (C ++ 11 onwards).
- General polymorphic function wrapper std :: function (C ++ 11 onwards). Two uses functors:
#include<iostream>
#include<functional>
using namespace std;
int main(){
greater<int> ig;
cout<<boolalpha<<ig(3,5)<<endl; //a
cout<<boolalpha<<greater<int>()(5,3)<<endl; //b
return 0;
}
After a row is added by Functor objects () parameter, the call Functor overloaded operator () functions defined in the function. b row by contact with the Functor class (), calling the constructor Functor class, generates a temporary function object, and the temporary object call operator ().
Compile and run the program, the result is:
false
true
STL functor is defined in the key functional header file, it is divided into the following categories: