问题描述
我想知道标准C ++中是否有一种方法可以声明一个指向具有相同签名的任何类的成员函数的指针.例如,X和Y具有相同签名的echoX和echoY方法
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; }
};
某些C ++实现通过扩展允许此功能(例如,VCL使用__closure
关键字).
Some C++ implementations allow this functionality via extensions (e.g VCL makes use of the __closure
keyword).
typedef int (__closure *IntFunPtr)(int);
现在,编写一个能够调用X::echoX
或Y::echoY
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.
谢谢
推荐答案
您可以创建一个通用的模板化函数,该函数接受您感兴趣的签名,传入对象的实例以及指向成员函数的指针.例如:
You could create a generic templated function which accepts the signature you are interested in, pass in the instance of the object and the pointer to the member function. For example:
template<typename T>
void CallObjectMethod(int(T::*func)(int), T& obj, int val)
{
cout << (obj.*func)(val);
}
现在像您在示例中提到的那样调用它:
Now to call it like you mentioned in your example:
X x, x1;
CallObjectMethod(&X::echoX, x, 10);
CallObjectMethod(&X::echoX, x1, 20);
对于对象Y,您可以执行以下操作:
For object Y you could do something like:
Y y, y1;
CallObjectMethod(&Y::echoY, y, 10);
CallObjectMethod(&Y::echoY, y1, 20);
这篇关于通用成员函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!