Http://www.cnblogs.com/runnyu/p/6010101.html
Imitation function: function object;
An imitation function (functors) is actually an object that overloads the operator ()
#include <iostream>
using namespace std;
Template<typename t>
struct m_plus
{
T operator () (const t& x, const t& y) {return x + y;}
};
int main (int argc, char *argv[])
{
//define its object invoke its operator ()
m_plus<int> op;
cout << op (1, 2) << Endl;
Generate an Anonymous object This is the main use of the imitation function
cout << m_plus<int> () (1, 2) << Endl;
return 0;
}
1. Imitation functions can have their own state, and function pointers are not (some use template or static variables can be implemented).
We can do this by using an imitation function:
#include <iostream>
using namespace std;
Template<typename T, t add>
struct m_plus
{
m_plus () {_add = add;}
T operator () (const t& x) {return x + _add;}
The affine function can have its own state
int _add;
int main (int argc, char *argv[])
{
m_plus<int, 10> op;
cout << op (m) << Endl;
cout << op << endl;
return 0;
}
2. Imitation functions can be used in combination with function adapters.
For example, if we want to use the COUNT_IF algorithm to compute the number of elements in the container that are greater than 10.
If we use greater<int> as a discriminant (two yuan), and count_if only accept a unary discriminant, then we need to work with the function adapter.
and function pointers can not be used directly with the function adapter, specifically in the analysis of bind2nd will be mentioned.
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm >
using namespace std;
int main (int argc, char *argv[])
{
vector<int> coll{1, 3, 5, 7, 9, One,};
Then there are the specific implementations of bind2nd
cout << count_if (Coll.begin (), Coll.end (), bind2nd (Greater<int> (), ten)) << Endl;
return 0;
}