Bind is a standard library function of c++11, which is defined in functional. Bind can be thought of as a generic function adapter that accepts a callable object and generates a new callable object to ' fit into the object's argument list.
The general form of calling Bind is:
Auto newcallable = bind (callale,arg_list);
wherenewcallable itself is a callable object,arg_list is a comma-separated argument list corresponding to the given callable parameter. That is, when we call Newcallalbe , we call callableand pass it to the arguments in the arg_list .
The parameters in arg_list may be protected in the form of a _n name, where n is an integer. These parameters are "placeholders" that represent newcallable, which occupy the position of the arguments passed to newcallable . The value n represents the parameter position in the generated callable object: _1 is the first parameter of newcallable , _2 is the second and so on.
Say so much maybe you get a little confused, no hurry let's take a look at a few simple code demos, and then go back and look at the instructions, everything you know.
#include <iostream>using namespace std; #include <functional>//use Bind-referenced header file using namespace placeholders;/ /Use bind namespace void fun (int a=0,int b=0,int c=0,int d=0,int e=0) {cout<< "a=" <<a<<endl << "b=" <<b<<endl << "c=" <<c<<endl << "d=" <<d<<endl << "e= "<<e<<endl <<" a+b+c+d+e= "<<A+B+C+D+E<<ENDL;} void Main (void) {int a=1, b=2, c=3, d=4, e=5; Auto G2=bind (fun,a,b,_1,d,_2); The first parameter of BIND is the function to be bound, and the number of arguments is the number of parameters of the bound function itself G2 (6,c,e); The mapping of G2 is Fun (a,b,6,d,c); Because of the bind parameter _1, and _2 's qualification, the E inside G2 is not mapped. /* Output Result: a=1 b=2 c=6 d=4 e=3 a+b+c+d+e=16 */G2 (c,e,6,7); The mapping of the G2 is Fun (a,b,c,d,e); G2 in 6,7 is not mapped because of the bind parameter _1, and _2 's qualification. /* Output Result: a=1 b=2 c=3 d=4 e=5 a+b+c+d+e=15 */Auto G1=bind (fun,a,b,_2,d,_1); G1 (c,e); The _1 and _2 in Bind are swapped, G1 map to Fun (A,B,E,D,C); /* Output Results: A=1 b=2 c=5 d=4 e=3 a+b+c+d+e=15 * Auto lab=[] (char I,char k) {cout<< "i=" <<i<<endl << "k=" <<k<<endl; }; Auto G3=bind (lab,_5,_3); G3 (' A ', ' B ', ' C ', ' d ', ' e '); /* Output Result: i=e k=c */Auto G4=bind (lab,_2,_4); G4 (' A ', ' B ', ' C ', ' d ', ' e '); /* Output Result: i=b K=d */System ("Pause");}
A preliminary understanding of c++11 bind