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.
Your code as it is in your question does not compile. But after fixing some syntax errors etc. your code actually does compile.
Compare it to your code to find out where the error came from.