FAQ 38.02 Can pointers to nonstatic member functions be passed to signal handlers, X event call-back handlers, and so on, that expect C-like function pointers?

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 } 

(1) ERROR: Cannot do this

(2) Good



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net