如何使用升压绑定一个成员函数 [英] How to use boost bind with a member function

查看:148
本文介绍了如何使用升压绑定一个成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code使CL.EXE崩溃(MS VS2005)。结果
我想使用升压绑定来创建一个函数来调用一个MyClass的方法:

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:

#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?

推荐答案

使用以下代替:

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

此转发传递给函数的对象使用占位函数的第一个参数 - 你要告诉的 Boost.Bind 的如何处理的参数。随着你的前pression它会尝试跨preT它为不接受参数的成员函数。结果
例如参见这里 或的这里常见的使用模式。

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

注意VC8s CL.EXE定期的 Boost.Bind 的误用崩溃 - 如果有疑问,使用测试用例与海湾合作委员会,你可能会得到很好的提示类的模板参数绑定的-internals用,如果你通过输出读取实例化。

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - 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.

这篇关于如何使用升压绑定一个成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆