|
|
Subject:
Generic C++ Function passing a function question
Category: Computers > Programming Asked by: mtb_man-ga List Price: $5.00 |
Posted:
03 Aug 2004 20:41 PDT
Expires: 04 Aug 2004 20:58 PDT Question ID: 383225 |
I have a simple C++ class. I want to pass one member function of the class the address of another member function of the same class and then call that passed function. I know this is doable if a static function is passed as the function to be called. I need the function to be called to be non-static. I am wondering if there is a way to convince the compiler to not only pass the address of a non-static member function but to call it as well. I have some sample code below and I get a compile error where indicated: class A; typedef void (*(A::func))(int i); // also does not work if "typedef void (*func)(int i);" class A { public: void a( func f ) { f( 123 ); printf( "A::a\n" ); } void b() { printf( "A::b\n" ); a( c ); ////<<<<< COMPILE ERROR HERE } void c(int i) { printf( "A::c, i=%d\n", i ); } }; The answer "It is not possible and here's the documented reason why" is acceptable too... | |
|
|
There is no answer at this time. |
|
Subject:
Re: Generic C++ Function passing a function question
From: chinchilla-ga on 04 Aug 2004 05:06 PDT |
for member functions you use a slightly different syntax than for class methods. instead of typedef void (*(A::func))(int i); use typedef void ((A::*func))(int i); since you want to have a pointer to a member function, to use it (in method a), do this by (this->*f) (123); the `this' pointer is necessary, since the compiler does not assume a `this' by default, as for normal method calls. Also you have to call a (in method b) by a(&A::c); since the method itself (c) is still located in the class, not in the object. |
Subject:
Re: Generic C++ Function passing a function question
From: mtb_man-ga on 04 Aug 2004 07:28 PDT |
Awesome answer - I was close but would have never figured out the correct syntax. Can you possibly point me to where this would be documented inline or in a popular C++ book? Also, please post your comment as an answer so I can pay you - you earned the money!!! |
If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you. |
Search Google Answers for |
Google Home - Answers FAQ - Terms of Service - Privacy Policy |