Don't.
Because a member function is meaningless without an object to invoke it on, youcan't do this directly (if The X Window System was rewritten in C++, it wouldprobably pass references to
objects around, not just pointers tofunctions; naturally the objects would embody the required function andprobably a whole lot more).
As a patch for existing software, use a top-level (non-member) function as awrapper which takes an object obtained through some other technique.Depending on the routine you're calling, this "other technique" might betrivial or might require a little work
on your part. The system call thatstarts a thread, for example, might require you to pass a function pointeralong with a
void*, so you can pass the object pointer in thevoid*. Many real-time operating systems do something similar for thefunction that starts a new task. Worst case you could store the objectpointer in a global variable; this might be required
for Unix signal handlers(but globals are, in general, undesired). In any case, the top-level functionwould call the desired member function on the object.
Here's an example of the worst case (using a global). Suppose you want tocall
Fred::memberFn() on interrupt:
public:
void memberFn();
static void staticMemberFn(); // A static member function can usually handle it
...
};
// Wrapper function uses a global to remember the object:
Fred* object_which_will_handle_signal;
void Fred_memberFn_wrapper()
{
object_which_will_handle_signal->memberFn();
}
int main()
{
/* signal(SIGINT, Fred::memberFn); */ // Can NOT do this
signal(SIGINT, Fred_memberFn_wrapper); // OK
signal(SIGINT, Fred::staticMemberFn); // OK usually; see below
...
}
Note: static member functions do not require an actual object to beinvoked, so pointers-to-static-member-functions areusually type-compatible with regular pointers-to-functions. However,although it probably works on most compilers,
it actually would have to be anextern "C" non-member function to be correct, since "C linkage"doesn't only cover things like name mangling, but also calling conventions,which might be different between C and C++.