如何使用std :: bind将成员函数设置为回调 [英] How to set a member function as callback using std::bind

查看:1348
本文介绍了如何使用std :: bind将成员函数设置为回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储函数回调的类,另一个有一个我想设置为回调的成员函数,如下所示:

I have a class that stores a function callback, and another on which has a member function that I want to set as a callback, like this:

using namespace std::placeholders;

class A {
    typedef std::function<void(int)> Callback;
    Callback callback;
    A() {}
    A(Callback f) : callback(f);
    do_something(int x) { callback(x); }
}

class B {
    A a;
    void function(int x) { printf("%d", x); }
    B() 
    {
         a = A( std::bind(&B::function, this, _1) );
    }

当我这样做并尝试调用回调函数时, MSVC上的函数调用错误。我在这里做错了什么?

When I do this and try to call the callback function, I get an invalid function call error on MSVC. What am I doing wrong here?

编辑01/21/2014

正如axalo所指出的,这段代码没有错误(除了一些错别字)。它编译。但是我正在做一些测试,并且我遇到了一个奇怪的行为:当我在构造函数中使用'this'指针时,即

As axalo pointed out, there is no error in this code (apart from some typos). It does compile. But i'm doing some testing, and I'm getting a weird behaviour: When I use 'bind' with the 'this' pointer on the contructor, i.e.,

B() { a = A( std::bind( &B::function, this, _1)); }

'this'指针与实际指向类实例的指针不同,而if我这样做:

the 'this' pointer is different from the actual pointer to an instance of the class, while if I do this:

void helper() = { a = A( std::bind( &B::function, this, _1)); }
B() {  }

从一个实例中调用helper正确的'this'指针。这种行为是否正确?我不应该相信构造函数中'this'指针的值吗?

And call helper() from an instance, I get the correct 'this' pointer. Is this behaviour correct? I should not trust the value of the 'this' pointer in the constructor?

谢谢。

Thanks.

推荐答案

你的代码在你的问题中没有被编译。
但是在修正了一些语法错误之后,你的代码实际上编译了。

Your code as it is in your question does not compile. But after fixing some syntax errors etc. your code actually does compile.

using namespace std::placeholders;

class A
{
public:
    typedef std::function<void(int)> Callback;
    Callback callback;

    A() {}

    A(Callback f) : callback(f) {}

    void do_something(int x)
    {
        callback(x);
    }
};

class B
{
    A a;

    void function(int x)
    {
        printf("%d", x);
    }

    B()
    {
        a = A(std::bind(&B::function, this, _1));
    }
};

将它与您的代码进行比较,以找出错误来自哪里。

Compare it to your code to find out where the error came from.

这篇关于如何使用std :: bind将成员函数设置为回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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