boost::bind介绍

boost::bind介绍
bind的中文翻译是"绑定",它的作用就是把参数与象函数一样的"东西"进行"绑定",然后象
函数一样运行.那象函数一样的"东西"到底是什么东西呢?
象函数一样的"东西"还挺多的.
int f1();
free function,这当然是一种.
int C::method();
某个class的method,当然也是一种.
typedef int (*pfunc)();
pfunc = f1;
函数指针,也是一种.
class C
{
public:
void operator()();
};
C obj;
obj(); //这是什么?看上去象函数调用.
//它等于 obj.()() --- 如此怪异的东西
//第一个()是函数名称,第二个()才是函数调用符
上面的class C有个标准名称,functor.自然它也属于象函数一样的"东西".
大概就这么点了吧,其他的反正现在是想不起来了,或许boost::function实现的"委托"也算一种
(不敢肯定,还没研究).
下面看看bind是怎样把参数依次与各个象函数一样的"东西""绑定"的.
1. bind free function
int add(int x, int y)
{
return x + y;
}
add(1, 2) <===> boost::bind(add, 1, 2)
int add1(int x)
{ <===> boost::bind(add, _1, 1)(x);
return add(x, 1); 其中 _1 是placehold(占位符),会被x所取代
}
add(x, y) <===> boost::bind(add, _1, _2)(x, y);
<===> boost::bind(add, _2, _1)(y, x);
add(x, x) <===> boost::bind(add, _1, _1)(x, y)
<===> boost::bind(add, _2, _2)(y, x)
C Add(const C &objX, cinst C &objY)
<===> boost::bind(Add, boost::cref(_1), boost::cref(_2))(objX, objY)
由于是非buildin type, 所以通过reference可能更有效率.默认情况下boost::bind的参数都是copy一份,不是很
有效率.
2. bind functor
struct F
{
int operator()(int a, int b) { return a - b; }
bool operator()(long a, long b) { return a == b; }
};
F f;
int x = 104;
bind<int>(f, _1, _1)(x); // f(x, x), i.e. zero
bind<int>(F(), _1, _1)(x); //F()是匿名object
3. bind class method
struct X
{
bool f(int a);
};
X x;
shared_ptr<X> p(new X);
int i = 5;
bind(&X::f, boost::ref(x), _1)(i); //x.f(i)
bind(&X::f, x, _1)(i); //x_copy = x, x_copy.f(i), 效率没有上一行代码高
bind(&X::f, &x, _1)(i); //(&x)->f(i),索性传指针
bind(&X::f, p, _1)(i); //p是smart pointer object,所以也有copy动作
//p_copy = p, p_copy->f(i)
bind(&X::f, boost::ref(p), _1)(i); //比上面一行,高效一点
4. Misc.
add(add(1, 2), add(3, 4) <===> boost::bind(add, boost::bind(add, 1, 2), boost::bind(add, 3, 4))
boost::bind支持嵌套
bind的返回值呢?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值