#include <iostream>#include<functional>using namespacestd;intFuncintAintb) { returnA +b;}classfoo{ Public: intFuncintAintb) {returnA +b; }};intMain () {Auto Bf1= Std::bind (func,Ten, std::p laceholders::_1); cout<<BF1 ( -) <<Endl; Foo F; Auto BF2= Std::bind (&Foo::func, F, std::p laceholders::_1, std::p laceholders::_2); cout<<BF2 ( -, -) <<Endl; Std::function<int(int) > BF3 = Std::bind (&foo::func, F, std::p laceholders::_1, -); cout<<BF3 ( -) <<Endl; 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.
Example: Bf1 is a two-parameter common function of the first parameter is bound to 10, generated a new parameter of the callable body; BF2 is to bind a class member function to a class object and generate a new callable entity like a normal function; BF3 is to bind the class member function to the class object and the second parameter, resulting in a new Std::function object. To understand the above example, here are 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
C++11 bind