简体   繁体   English

如何使用std :: bind将成员函数设置为回调

[英]How to set a member function as callback using 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) );
    }

When I do this and try to call the callback function, I get an invalid function call error on MSVC. 当我这样做并尝试调用回调函数时,在MSVC上收到无效的函数调用错误。 What am I doing wrong here? 我在这里做错了什么?

EDIT 01/21/2014 编辑2014年1月21日

As axalo pointed out, there is no error in this code (apart from some typos). 正如axalo所指出的,此代码没有错误(除了一些错字)。 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, ie, 但是我正在做一些测试,并且得到一种奇怪的行为:当我在构造函数上使用“ bind”和“ this”指针时,即

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

the 'this' pointer is different from the actual pointer to an instance of the class, while if I do this: 'this'指针不同于指向类实例的实际指针,而如果我这样做:

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

And call helper() from an instance, I get the correct 'this' pointer. 并从实例调用helper(),我得到了正确的“ this”指针。 Is this behaviour correct? 这种行为正确吗? I should not trust the value of the 'this' pointer in the constructor? 我不应该相信构造函数中“ this”指针的值吗?

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. 将其与您的代码进行比较,以找出错误的出处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM