大龙的博客

常用链接

统计

最新评论

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的返回值呢?

posted on 2007-01-08 15:40 大龙 阅读(10382) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理