[英]How to store a member function pointer through an interface
我会创建一个这样的界面:
class IMother {
public:
// This getter return a map which contains a member functer pointer
virtual map<string, void (IMother::*)()> getMap() const = 0;
virtual ~IModule() {};
};
然后,创建一个子项并覆盖getter,以便返回仅包含Child_1成员函数指针的映射
class Child_1 : public IMother {
private:
map<string, void (Child1::*)(int)> _map;
public:
void do_something_1(int a) {
// Something...
}
void do_something_2(int a) {
// Something...
}
virtual map<string, void (Child1::*)(int)> getMap() {
_map["do_1"] = &do_something_1;
_map["do_2"] = &do_something_2;
return _map;
}
我以为我能够让它发挥作用,因为在我看来,我认为Child1是一个IMother,所以我有权写这个,但我不能......
int main() {
IMother *mother = new Child_1;
// I don't know how run a method through a map
mother->getMap["do_1"](42); // Not seem to work
return 0;
}
有没有办法通过接口存储成员函数指针?
IMother::getMap
和IChild::getMap
有不同的返回类型。 仅当这些返回类型是协变的时,才允许这样做。 尽管IMother
和IChild
是协变的, std::map<...IMother...>
和std::map<...IChild..>
不是。 所以你的例子不能用错误编译: invalid covariant return type
这里几乎没有问题:
首先,指向成员的指针是不正确的:
这个:
_map["do_1"] = &do_something_1; _map["do_2"] = &do_something_2;
应该:
_map["do_1"] = &Child1::do_something_1; _map["do_2"] = &Child1::do_something_2;
其次,IMother和Child1上的getMap()的返回类型不同,因为一个不接受params和一个指向IMother成员的指针,另一个接受一个int并且是一个指向Child1成员的指针。 这两个差异导致返回类型在C ++中不同。
IMother:
map<string, void (IMother::*)()>
Child1:
map<string, void (Child1::*)(int)>
由于返回类型不同,因此Child1没有覆盖IMother中定义的所有纯虚函数,因此无法实例化Child1的实例。
第三,您的成员函数调用不正确。 在调用之前,成员函数仍然需要提供“成员”。 例如
class SomeClass; typedef void (SomeClass::* SomeClassFunction)(void); void Invoke(SomeClass *pClass, SomeClassFunction funcptr) { (pClass->*funcptr)(); };
话虽如此,我会看看stl功能标题。 stl函数库将允许您编写以下内容,然后以比内置C ++语法更简单的语法调用它们:
typedef std::function<float (float)> MyFuncType;
map<sting, MyFuncType> myFuncs;
myFuncs["myCustomSin"] = &SomeClass::SomeCustomSinFunc;
myFuncs["cSin"] = &sin;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.