Take a look at the following example:
#include <iostream>
using namespace std;
class Test {
public:
int fun1(int x) { return x+1; }
};
typedef int (Test::*PtrType)(int);
void call(Test& self, PtrType prt) {
cout << (self.*ptr)(2) << endl;
}
int main() {
Test t;
call(t, &Test::fun1);
return 0;
}
The line typedef int (Test::*PtrType)(int);
defines simple name for the type to the class method. The parenthesis around (Test::*PtrType)
are important; PtrType
is the new defined type (Although you could do without the typedef, and put the whole signature in the call
function arguments, such approach is strongly discouraged).
The expression (self.*ptr)(2)
calls the method pointed by your pointer ptr
, passing 2 as its argument. Again the key point is putting parenthesis around (self.*ptr)
.
The last point to remember is that you cannot skip &
when setting the value of the pointer (&Test::fun1
), even as it is possible with regular function.
You can make your code a little neater, if you use templates:
template <typename PtrT>
void call(Test& self, PtrT ptr) {
cout << (self.*ptr)(2) << endl;
}
No typedef is necessary in such case, however, you must still remember about parenthesis in the invocation.
If you are compiling with the new C++0x standard, you can use std::function
or std::bind
.