C++ 如何使用带有成员函数的 boost 绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2304203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:58:01  来源:igfitidea点击:

How to use boost bind with a member function

c++boostboost-bindboost-function

提问by hamishmcn

The following code causes cl.exe to crash (MS VS2005).
I am trying to use boost bind to create a function to a calls a method of myclass:

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

What am I doing wrong?

我究竟做错了什么?

回答by Georg Fritzsche

Use the following instead:

请改用以下内容:

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

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bindhow to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. hereor herefor common usage patterns.

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

Note that VC8s cl.exe regularly crashes on Boost.Bindmisuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

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