C++ 如何将boost绑定与成员函数一起使用

C++ 如何将boost绑定与成员函数一起使用,c++,boost,boost-bind,boost-function,C++,Boost,Boost Bind,Boost Function,以下代码导致cl.exe崩溃(MS VS2005)。 我正在尝试使用boost bind创建一个函数来调用myclass的方法: #include "stdafx.h" #include <boost/function.hpp> #include <boost/bind.hpp> #include <functional> class myclass { public: void fun1() { printf("fun1()\n");

以下代码导致cl.exe崩溃(MS VS2005)。
我正在尝试使用boost bind创建一个函数来调用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;
}
#包括“stdafx.h”
#包括
#包括
#包括
类myclass{
公众:
void fun1(){printf(“fun1()\n”);}
void fun2(int i){printf(“fun2(%d)\n),i);}
无效测试(){
boost::函数f1(boost::bind(&myclass::fun1,this));
boost::函数f2(boost::bind(&myclass::fun2,this));//失败
f1();
f2(111);
}
};
int main(int argc,char*argv[]){
myclass mc;
mc.testit();
返回0;
}

我做错了什么?

请使用以下选项:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
boost::function f2(boost::bind(&myclass::fun2,this,_1));
这将使用占位符将传递给函数对象的第一个参数转发给函数-您必须告诉Boost.Bind如何处理这些参数。对于表达式,它将尝试将其解释为不带参数的成员函数。
有关常见的使用模式,请参见或


请注意,VC8s cl.exe经常在Boost.Bind误用时崩溃-如果有疑问,请使用带有gcc的测试用例,如果通读输出,您可能会得到很好的提示,如绑定内部的模板参数实例化。

您是否有机会对此提供帮助?这很相似,但是
std::function
给出了一个错误谢谢你,这有点让人困惑,但是你的回答救了我一命!