bind是一组用于函数绑定的模板。在对某个函数进行绑定时,可以指定部分参数或全部参数,也可以不指定任何参数,还可以调整各个参数间的顺序。对于未指定的参数,可以使用占位符_1、_2、_3来表示。-1表示绑定后的函数的第1个参数,_2表示绑定后的函数的第2个参数,其他依次类推。
bind可以绑定到普通函数、函数对象、类的成员函数和类的成员变量。下面分别进行介绍。
1、普通函数
1 void nine_arguments(int i1,int i2,int i3,int i4,int i5,int i6,int i7,int i8,int i9); 2 int i1=1, i2=2, i3=3, i4=4, i5=5, i6=6, i7=7, i8=8, i9=9; 3 bind(nine_arguments,_9,_2,_1,_6,_3,_8,_4,_5,_7(i1,i2,i3,i4,i5,i6,i7,i8,i9); 4 bind(nine_arguments,i9,i2,i1,i6,i3,i8,_1,_2,_1)(i8,i9); 5 bind(nine_arguments, i9,i2,i1,i6,i3,i8,i4,i5,i7)();
1 class CStudent 2 { 3 public: 4 void operator() (string strName, int nAge) 5 { 6 cout << strName << " : " << nAge << endl; 7 } 8 }; 9 bind(CStudent(), "Mike", _1)(12);
1 struct TAdd 2 { 3 int Add(int x,int y) 4 { 5 return x+y; 6 } 7 }; 8 TAdd tAdd; 9 TAdd *p = new TAdd(); 10 shared_ptr<TAdd> *q(p); 11 bind(TAdd::Add, tAdd, 2, 3)(); 12 bind(TAdd::Add, p, 2, 3)(); 13 bind(TAdd::Add, q, 2, 3)();
1 void Output(const string &name) 2 { 3 cout << name << endl; 4 } 5 6 map<int, string> map1; 7 for_each(map1.begin(), map1.end(), bind(Output, bind(map<int, 8 string>::value_type::second, _1)));
1 vector<CPerson> vctPerson; 2 sort(vctPerson.begin(), vctPerson.end(), bind(less<int>(), 3 bind(CPerson::GetAge, _1), bind(CPerson::GetAge, _2)));
1 count_if(vctNum.begin(), vctNum.end, bind(logic_and<bool>(), 2 bind(greater<int>(), _1, 20), bind(less<int>(), _1, 30)));
1、对于指定了值的参数,bind返回的函数对象会保存这些值,并且缺省是以传值方式保存的。考虑下面的代码:
1 void inc(int &a) { a++; } 2 int n = 0; 3 bind(inc, n)();
1 bind(inc, ref(n))(); // n现在等于1了
1 typedef function<void (int)> Func; 2 vector<Func> vctFunc; 3 for_each(vctFunc.begin(), vctFunc.end(), bind(_1, 5)); // 编译出错
1 apply<void> a; // void是函数对象的返回值类型 2 a(f); // 相当于调用f() 3 a(f, x); // 相当于调用f(x) 4 a(f, x, y); // 相当于调用f(x, y)
1 for_each(vctFunc.begin(), vctFunc.end(), bind(apply<void>(), _1, 5));