The bind () and function () functions provide C + + control over functions and objects in the standard library of Std.
Bind () is called "binding", and bind () is related to the function, so it is bound to a function, please look at the code
int f (intchardouble); ' C ' 1.2); // binds the second and third arguments of the F () function call, returns a new function object as FF, with only one parameter of type int int x = FF (7); // F (7, ' C ', 1.2);
We cannot bind a parameter of an overloaded function with bind (), we must explicitly indicate the version of the overloaded function that needs to be bound
function () is a owning anything that can be "(...)" The type of the value called by the symbol. In particular, the return result of bind can be assigned to the function type. function is very easy to use. More intuitively, you can think of functions as a data type that represents a function, just like a function object. Just plain data types represent data, and function represents the abstract concept of functions. ), take a look at the code
function<float(intXintY) > F;//constructs a function object that can represent a function with a return value of float, two parameters of Int,int structInt_div {//constructs a function object type that can be called by using "()" float operator() (intXintYConst{return((float) x)/y;}; }; F= Int_div ();//Assign Valuecout<< F (5,3) <<endl;//called by a function objectStd::accumulate (b, E,1, f);//Perfect Delivery
The member function can be seen as a free function with extra parameters, so take a look at the code
structX {intFooint); }; function<int(X*,int) > F;//the so-called extra parameter is the first parameter that the member function defaults to, that is, the this pointer to the object that called the member functionf = &X::foo;//point to member functionsx x; intv = f (&x,5);//call X::foo () with parameter 5 on object xfunction<int(int) > FF = Std::bind (f, &x, _1);//the first parameter of F is &xv = FF (5);//Call X.foo (5)
function is useful for callback functions, passing operations as parameters, and so on. It can be seen as a substitute for function object mem_fun_t, pointer_to_unary_function, etc. in the C++98 standard library. Similarly, bind () can also be seen as a substitute for bind1st () and bind2nd (), and certainly more powerful and flexible than they are
Bind () and function for new features of C + + 11