I'm wondering if there's a way in standard C++ (it seems this is not supported but perhaps I didn't look hard) to declare a pointer to any class' member function with the same signature. For example, X and Y have echoX and echoY methods with the same signature
class X{
int val;
public:
int echoX(int v) {
val = v;
return v; }
int getValue() const { return val; }
};
class Y{
int val;
public:
int echoY(int v) {
val = v;
return v;
}
int getValue() const { return val; }
};
Some C++ implementations allow this functionality via extensions (e.g VCL makes use of the __closure
keyword).
typedef int (__closure *IntFunPtr)(int);
Now, it's trivial to write a function that is able to call either X::echoX
or Y::echoY
void CallObjectMethod(IntFunPtr fPtr, int val){
fPtr(val);//this can call any member method that accepts an int and returns an int
}
X x, x1;
CallObjectMethod(&x.echoX,4);
CallObjectMethod(&x1.echoX,20);
Y y, y1;
CallObjectMethod(&y.echoY,10);
CallObjectMethod(&y1.echoY,15);
This functionality can be useful for implementing event handlers, among other things.
Thank you