I have a question regarding callbacks using tr1::function. I've defined the following:
class SomeClass {
public:
typedef std::tr1::function<void(unsigned char*, int)> Callback;
void registerCallback(Callback);
private:
Callback callback;
}
I've defined another class:
class SomeOtherClass {
void myCallback(unsigned char*, int);
}
Now I want to register my function 'myCallback' as callback at class 'SomeClass'using the method 'registerCallback'. However, it is not working. I've had a look on the boost documentation on the function and it seems legit to use (member) methods of a class for callbacks. Am I wrong?
Thanks in advance!
Use templates:
Such like this. And use it:
Member functions have an implicit first parameter, a
this
pointer so as to know which object to call the function on. Normally, it's hidden from you, but to bind a member function to std::function, you need to explicitly provide the class type in template parameter.Output:
You called me?
;the function
void (*)(unsigned char*, int)
is a free function, which is a different type fromvoid (SomeOtherClass::*)(unsigned char*, int)
, thus the error. You need an object to call the latter, while the former is a free function.Look at the possible solutions listed in the Boost documentation
Another possibility is that your
SomeOtherClass::myCallback
is private, so you do not have access to it.Why all this complicated mumbo-jumbo?
Why not create a class as thus (for example)
Then just create classes that inherit this class (and redefine the method
RunMouseOverCallback
)Then Register function just needs to be
The register method will just call the method and the object will have all that it needs.
Seems a bit simpler. Let the compiler do the work with pointers to functions etc.