function, bind is a feature in TR1, has been integrated into the C++0X/C++11
How to use
1. Using TR1
Header file: <tr1/functional>
std::tr1::function
std::tr1::bind
std::tr1::placeholders::_N
2. Using C++0X/11
Header file: <functional>
std::function
std::bind
std::placeholders::_N
Role
Bind binds an existing function with a specific parameter and returns a new callable object function to be used
Example
A subtraction calculation function exists:
STD::TR1;
STD::TR1::p laceholders;
Calcsub (b) { B;}
1. Bind all Parameters
function<int ()bind (&3);
Bind calcsub to argument 10 and 3 using bind, resulting in a int(void)
type of function (callable object)
So, call fun: fun()
equivalent tocalcSub(10,3)
2. Binding several parameters
function<int (int)bind (&_1);
That is, calcSub(10, _1)
the callable object fun
that bind produces.
Where the placeholder _1
represents: fun
The 1th parameter will be the second parameter of the calcsub
So fun
there is a parameter, type =calcsub the type of the second argument =int
Then: fun(3)
equivalent tocalcSub(10,3)
Placeholders::_n represents the nth parameter of a generated callable object
function<int (int,int)bind (&_1);
That is, calcSub(_2,_1)
the callable object fun
that bind produces.
and through the placeholder declaration:The 2nd parameter of fun will be the first argument (int) of Calcsub, and the 1th parameter of fun will be the second argument (int) of calcsub.
So fun
there are two parameters, and the type is int
So:fun(10,3) = calcSub(3,10)
3. Bind can also bind class member functions
If there is a class:
MyClass {
Public
Memfun (b) {...}
};
If you want to bind member function Calcsub, you cannot forget that the first parameter of Calcsub is myclass* this
Ins
function<void (string,int)bind (&&_1);
_2 declared: The 2nd parameter of fun as the second argument of memfun (int)
_1 declared: The 1th parameter of fun as the third parameter of Memfun (string)
So the fun parameter isstring,int
So:func("xxx", 10)等价于ins.calcSub(10, "xxx");
function and bind of c++11