A pointer to a nonstatic member function cannot be passed into a routine that is expecting a pointer to a C-like function, since a nonstatic member function is meaningless without there being an object to which the nonstatic member function can be applied. To simulate this behavior, pass a pointer to a C-like function, and have that function obtain the object pointer through some other technique (such as storing it in a global). The C-like function would then call the desired nonstatic member function. For example, suppose x.f(int) were to be called on interrupt, where f(int) is a nonstatic member function of the class of object x. The following would accomplish the call (note that a static member function has the same type as a C-like function). #include <iostream> #include <signal.h> using namespace std; class Fred { public: void f(int n) throw(); static void staticMethod(int n) throw(); static void registerHandlerObject(Fred* p) throw(); private: static Fred* signalHandlerObject_; //the handler object }; void Fred::f(int n) { cout << "Fred::f()\n"; } void Fred::registerHandlerObject(Fred* p) { signalHandlerObject_ = p; } void Fred::staticMethod(int n) { Fred* p = Fred::signalHandlerObject_; p->f(n); } Fred* Fred::signalHandlerObject_ = NULL; int main() { //signal(SIGINT, Fred::f); <-- 1 Fred x; Fred::registerHandlerObject(&x); signal(SIGINT, Fred::staticMethod); <-- 2 }
|