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

新手上路,请多包涵

以下代码导致 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;
}

我究竟做错了什么?

原文由 hamishmcn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 484
1 个回答

请改用以下内容:

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

这会将传递给函数对象的第一个参数转发给使用占位符的函数 - 您必须告诉 Boost.Bind 如何处理参数。使用您的表达式,它会尝试将其解释为不带参数的成员函数。

有关常见的使用模式,请参见 此处此处

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

原文由 Georg Fritzsche 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题