2010-02-20 76 views
67

以下代码会导致cl.exe崩溃(MS VS2005)。
我想使用升压绑定来创建一个函数来调用一个MyClass的的方法:如何在成员函数中使用boost绑定

#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; 
} 

我在做什么错?

回答

89

改用以下:

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

此转发传递给函数的对象使用占位函数的第一个参数 - 你要告诉Boost.Bind如何处理的参数。用你的表达式,它会试图把它解释为不带任何参数的成员函数。
参见例如herehere的常用使用模式。

注意VC8s CL.EXE定期Boost.Bind滥用崩溃 - 如果有疑问,使用测试用例用gcc,你可能会得到很好的提示,如模板参数绑定 -internals被实例化,如果您通读输出。

+0

任何机会,你可以帮助这个http://stackoverflow.com/questions/13074756/how-to-avoid-static-member-function-when-using-gsl-with-c?它是相似的,但'std :: function'给出了一个错误 – 2012-10-29 04:28:22

+0

谢谢,这有点令人困惑,但你的答案拯救了我的培根! – portforwardpodcast 2014-06-20 02:28:11

相关问题