[MOC062066]boost bind常见使用方法汇总

来源:互联网 发布:深航飞行员知乎 编辑:程序博客网 时间:2024/06/06 04:54

//moC062066

//blog.csdn.net/moc062066

//2012年4月13日 14:40:26



bind 自由函数、成员函数、函数对象


1.自由函数


1.1 向原始函数 fun 绑定所有的参数
1.2 绑定一部分参数
1.3 不绑定参数


demo:
void fun( /* [in] */ int x, /* [in] */ int y){cout << x << "," << y << endl;}int main(int argc, char* argv[]){/****************bind 自由函数********************///3,4boost::function< void(int,int) > fptr;//预留两个占位符,说明有两个参数,故function那里有两个输入:int,int//实际上function<>里面要填的是bind了之后的函数声明,//否者如果<>里面要填将要被bind的那个函数的原型,要bind何用!!//bind的目的就在于改变函数原型//_1 是一个占位符参数,它的含义是“用第一个输入参数取代”。fptr = boost::bind(&fun,_1,_2);fptr(3,4);//5,3boost::function< void(int) > fptr2;fptr2 = boost::bind(&fun,_1,3);fptr2(5);//12,34boost::function< void(int) > fptr3;fptr3 = boost::bind(&fun,12,_1);fptr3(34);//8,9boost::function< void() > fptr4;fptr4 = boost::bind(&fun,8,9);fptr4();return 0;}


2.绑定函数对象
要有实例
class Func {public:void operator()( /* [in] */ int x, /* [in] */ int y) {cout << x << "," << y << endl;}};int main(int argc, char* argv[]){/***************************1*******************///1Func f;boost::function<void(int,int)> fptr;fptr = boost::bind(&Func::operator(),&f,_1,_2);fptr(100,1);////Func f;boost::function<void(int)> fptr2;fptr2 = boost::bind(&Func::operator(),&f,100,_1);fptr2(1);//Func f;boost::function<void(int)> fptr3;fptr3 = boost::bind(&Func::operator(),&f,_1,1);fptr3(100);//Func f;boost::function<void()> fptr4;fptr4 = boost::bind(&Func::operator(),&f,100,1);fptr4();/*******************************2****************/////Func f;boost::bind<void>(f,45,67)();//Func f;boost::bind<void>(f,_1,67)(45);//Func f;boost::bind<void>(f,45,_1)(67);//Func f;boost::bind<void>(f,_1,_2)(45,67);}


3. 类成员函数
要有实例

struct X{    bool f(int a);};X x;shared_ptr<X> p(new X);int i = 5;bind(&X::f, ref(x), _1)(i);// x.f(i)bind(&X::f, &x, _1)(i);//(&x)->f(i)bind(&X::f, x, _1)(i);// (internal copy of x).f(i)bind(&X::f, p, _1)(i);// (internal copy of p)->f(i)


原创粉丝点击