Boost::bind
/* Boost::bind 1) bind1st,bind2st函数绑定器,把二元函数对象变为一元函数对象。 2) mem_fun,把成员函数变为函数对象。 3) fun_ptr,把一般的全局函数变为函数对象。 4) boost::bind(),统一的接口实现以上所有的功能。 注意 1) 现在的类库最多可以支持9个参数。 2)在绑定一个成员函数时,bind 表达式的第一个参数必须是成员函数所在类的实例!理解这个规则的最容易的方法是,这个显式的参数将取替隐式的 this ,被传递给所有的非静态成员函数。细心的读者将会留意到,实际上这意味着对于成员函数的绑定器来说,只能支持八个参数,因为第一个要用于传递实际的对象。 3)当我们传递某种类型的实例给一个 bind 表达式时,它将被复制,除非我们显式地告诉 bind 不要复制它。要避免复制,我们必须告诉bind 我们想传递引用而不是它所假定的传值。我们要用 boost::ref 和 boost::cref (分别用于引用和 const 引用)来做到这一点,它们也是Boost.Bind 库的一部分。还有一种避免复制的方法;就是通过指针来传递参数而不是通过值来传递。 4) 通过 Boost.Bind, 你可以象使用非虚拟函数一样使用虚拟函数,即把它绑定到最先声明该成员函数为虚拟的基类的那个虚拟函数上。这个绑定器就可以用于所有的派生类。如果你绑定到其它派生类,你就限制了可以使用这个绑定器的类。 5)bind还可以绑定成员变量。 */ #include "stdafx.h" #include #include #include #include #include #include "boost/bind.hpp" 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(void){ std::vector ints; ints.push_back(7); ints.push_back(4); ints.push_back(12); ints.push_back(10); int count=std::count_if(ints.begin(), ints.end(), boost::bind(std::logical_and(), boost::bind(std::greater(),_1,5), boost::bind(std::less_equal(),_1,10)) ); std::cout << count << '\n'; std::vector::iterator int_it=std::find_if(ints.begin(),ints.end(), boost::bind(std::logical_and(), boost::bind(std::greater(),_1,5), boost::bind(std::less_equal(),_1,10)) ); if (int_it!=ints.end()) { std::cout << *int_it << '\n';} 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 v(2); //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)); return 0; }
boost::bind是标准程序库std::bind1st与std::bind2nd的一般化; 而boost::lambda::bind是一个表达式,用于生成lambda的functor。