A function object is essentially a class that implements the operator ()--parenthesis operator.
classadd{ Public: int operator()(intAintb) {returnA +b; }};intMain () {add add;//Defining function Objectscout << Add (3,2);//5System ("Pause"); return 0;}
The function pointer version is:
intAddfunc (intAintb) { returnA +b;} typedefint(*add) (intAintb);intMain () {add Add= &Addfunc; cout<< Add (3,2);//5System ("Pause"); return 0;}
Since there is no difference between a function object and a function pointer in how it is used, why use a function object? Very simply, the function object can carry additional data, and the pointer will not.
Here's an example of using additional data:
classless{ Public: Less (intnum): N (num) {}BOOL operator()(intvalue) { returnValue <N; }Private: intN;};intMain () {less isless (Ten); cout<< isless (9) <<" "<< isless ( A);//Output 1 0System ("Pause"); return 0;}
Bind is a mechanism that can pre-bind certain parameters of a specified callable entity to an existing variable, producing a new callable entity that is useful in the use of a callback function.
intFunc (intXinty) { returnX +y;}intMain () {//BF1 binds the first parameter of a common function with two parameters to 10, generating a new callable entity of a parameterAuto Bf1 = Std::bind (Func,Ten, std::p laceholders::_1); cout<<BF1 ( -);///< same as Func (Ten)System"Pause"); return 0;}
classa{ Public: intFunc (intXinty) {returnX +y; }};intMain () {a A; //BF2 binds a class member function to a class object, creating a new callable entity like a normal functionAuto BF2 = Std::bind (&A::func, A, std::p laceholders::_1, std::p laceholders::_2); cout<< BF2 (Ten, -);///< same as A.func (Ten)System"Pause"); return 0;}
Some things to note about using bind:
- (1) Bind pre-bound parameters need to pass specific variables or values in, for the pre-bound parameters, is Pass-by-value
- (2) For non-binding parameters, need to pass std::p laceholders go in, starting from the _1, in turn, increment. Placeholder is pass-by-reference.
- (3) The return value of BIND is a callable entity and can be assigned directly to the Std::function object
- (4) For binding pointers, arguments of reference types, the consumer needs to ensure that these parameters are available before callable entity calls
- (5) The This of a class can be bound by an object or a pointer
Reference: http://blog.csdn.net/crayondeng/article/details/9996625
C + + 's function object, bind function