[英]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.