您的位置:首页 > 其它

Boost学习笔记-bind

2009-02-25 16:59 561 查看
boost::bind 是标准函数 std::bind1st 和 std::bind2nd 的泛化,它可以将任何的函数,成员函数,函数对象,绑定成为一个无元的函数对象。而且bind对函数的支持远强于标准函数中的bind.
定义一个函数
int fun1(int a,int b)
{
std::cout<<"fun1 called "<<a<<"+"<<b<<"="<<a+b<<std::endl;
return a+b;
}
我们可以使用这种方法调用函数
boost::bind(fun1,6,7)();
相当于调用了 fun1(6,7);

我们也可以使用其中自带的占位符
boost::bind(fun1,_1,_1)(3);
其中_1是一个占位符,表示其值用调用时第一个参数代替。
这段代码相当于调用了 fun1(3,3);

我们也可以定义一个函数指针来存储这个函数对象
boost::function<int (int x, int y)> f2= fun1;
f2(22,33);

我们还可以对函数对象使用
struct F1
{
int s;
typedef void result_type;
void operator() (int x)
{
s += x;
}
};

F1 f = {0};
int array[] = {1,1,2,32};
std::for_each(array,array+4,boost::bind(boost::ref(f),_1));
assert(f.s==36);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: