The thing to know here is that a pointer to a member function is not the same as a pointer to a (standalone) function. The difference is that all member functions have a hidden first argument that is the this
pointer in the function. Therefore you need to have an instance of an object to actually be able to call the member function pointer.
Only static
member functions doesn't have this hidden first argument, as they don't have a this
pointer (static member function are for the whole class, not for a specific instance) and so can be used as a normal function pointer.
There are three ways of using member function pointers.
The first is to use a static member function, and have an argument to it that will be a pointer to the instance. This will of course only work if the system allows you to pass extra arguments to the function pointer. If (and I'm only guessing here) the second argument to
wait_event
is such a "userdata" pointer, then this can be used for it:wait_event(&staticTouched, this);
Then you make a static member function that calls the real function:
static void staticTouched(void* instance) { static_cast<UncouplerController*>(instance)->touched(); }
The second method is if the
wait_event
is a member of your class, in which case it can actually use its ownthis
pointer when calling the member function:void wait_event(void (UncouplerController::*func)(), ...) { // Do stuff... (this->func)(); // Call the member function pointer }
The third way is to use the new C++11
std::function
class, instead of member function pointers. This will make the event-handling system more generic, asstd::function
can be used to store normal functions, static member functions, non-static member functions and lambda expressions. Other than this, it's very similar to the second case:void wait_event(std::function<void()> func, ...) { // Do stuff... func(); // Call the function object }
Then to call the
wait_event
with the member function pointer, you usestd::bind
:wait_event(std::bind(&UncouplerController::touched, this), 0);
If the wait_event
function is the one pointed out by Lightness Races in Orbit, then you can't use member function pointers. And the first case in my list above is then wrong as the second argument is something completely different.