How to set a member function as callback using std

2019-08-15 07:24发布

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. What am I doing wrong here?

EDIT 01/21/2014

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)); }

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() {  }

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.

1条回答
走好不送
2楼-- · 2019-08-15 08:00

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.

查看更多
登录 后发表回答