如何使用boost成员函数进行绑定

以下代码导致cl.exe崩溃(MS VS2005)。
我正在尝试使用boost绑定来创build一个调用myclass方法的函数:

#include "stdafx.h" #include <boost/function.hpp> #include <boost/bind.hpp> #include <functional> class myclass { public: void fun1() { printf("fun1()\n"); } void fun2(int i) { printf("fun2(%d)\n", i); } void testit() { boost::function<void ()> f1( boost::bind( &myclass::fun1, this ) ); boost::function<void (int)> f2( boost::bind( &myclass::fun2, this ) ); //fails f1(); f2(111); } }; int main(int argc, char* argv[]) { myclass mc; mc.testit(); return 0; } 

我究竟做错了什么?

请改用以下内容:

 boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) ); 

这将传递给函数对象的第一个参数转发给使用占位符的函数 – 您必须告诉Boost.Bind如何处理参数。 随着你的expression,它会试图把它解释为不带任何参数的成员函数。
请参阅这里或这里的常见使用模式。

请注意,VC8s cl.exe定期崩溃Boost.Bind误用 – 如果有疑问使用gcc的testing用例,你可能会得到好的提示,如模板参数绑定 – 内部实例如果你通过输出。