bind並不是一個單獨的類或函數,而是非常龐大的家族,依據綁定的參數個數和要綁定的調用物件類型,總共有十個不同的形式,但它們的名字都叫bind.
bind接受的第一個參數必須是一個可調用對象f,包括函數,函數指標,函數對象和成員函數,之後bind接受最多9個參數,參數的數量必須與f的參數數量相等
_1,_2這些一直可以到9,是預留位置,必須在綁定運算式中提供函數要求的所有參數,無論是真實參數還是預留位置均可以。預留位置不可以超過函數參數數量。
綁定普通函數:
C++代碼
- #include<boost/bind.hpp>
- #include<iostream>
- using namespace std;
- using namespace boost;
-
- void fun(int a,int b){
- cout << a+b << endl;
- }
-
- int main()
- {
- bind(fun,1,2)();//fun(1,2)
- bind(fun,_1,_2)(1,2);//fun(1,2)
- bind(fun,_2,_1)(1,2);//fun(2,1)
- bind(fun,_2,_2)(1,2);//fun(2,2)
- bind(fun,_1,3)(1);//fun(1,3)
- }
-
-
- 3
- 3
- 3
- 4
- 4
#include<boost/bind.hpp>#include<iostream>using namespace std;using namespace boost;void fun(int a,int b){ cout << a+b << endl;}int main(){ bind(fun,1,2)();//fun(1,2) bind(fun,_1,_2)(1,2);//fun(1,2) bind(fun,_2,_1)(1,2);//fun(2,1) bind(fun,_2,_2)(1,2);//fun(2,2) bind(fun,_1,3)(1);//fun(1,3)}33344
綁定成員函數:
C++代碼
- #include<boost/bind.hpp>
- #include<iostream>
- #include<vector>
- #include<algorithm>
- using namespace boost;
- using namespace std;
-
- struct point
- {
- int x,y;
- point(int a=0,int b=0):x(a),y(b){}
- void print(){
- cout << "(" << x << "," << y << ")\n";
- }
- void setX(int a){
- cout << "setX:" << a << endl;
- }
- void setXY(int x,int y){
- cout << "setX:" << x << ",setY:" << y << endl;
- }
- void setXYZ(int x,int y,int z){
- cout << "setX:" << x << ",setY:" << y << "setZ:" << z << endl;
- }
- };
-
- int main()
- {
- point p1,p2;
- bind(&point::setX,p1,_1)(10);
- bind(&point::setXY,p1,_1,_2)(10,20);
- bind(&point::setXYZ,p2,_1,_2,_3)(10,20,30);
- vector<point> v(10);
- //for_each的時候只需要_1就可以了
- for_each(v.begin(),v.end(),bind(&point::print,_1));
- for_each(v.begin(),v.end(),bind(&point::setX,_1,10));
- for_each(v.begin(),v.end(),bind(&point::setXY,_1,10,20));
- for_each(v.begin(),v.end(),bind(&point::setXYZ,_1,10,20,30));
- }
-
- setX:10
- setX:10,setY:20
- setX:10,setY:20setZ:30
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- (0,0)
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30
- setX:10,setY:20setZ:30