简体   繁体   中英

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. 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, ie,

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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