所以我正在研究这个事件管理类(class)。我正在存储指向签名 void (Event*)
的成员函数的指针列表,其中 Event 只是一个当前存储一些随机数据的结构。
typedef boost::function<void(Event*)> Callback;
typedef vector<Callback> CallbackList;
class EventManager
{
public:
template<typename T>
void RegisterEventHandler(const std::string& type, void (T::*handler)(Event*), T* obj)
{
mCallbackList[type].push_back(boost::bind(handler, obj, _1));
}
void DispatchEvent(const std::string& type, Event* evt)
{
for(CallbackList::iterator it = mCallbackList[type].begin(); it != mCallbackList[type].end(); ++it)
{
Callback callback = (*it);
callback(evt);
}
}
private:
hash_map<std::string, CallbackList> mCallbackList;
};
我想知道,我是否可以派生不同版本的 Event,并将指向这些成员函数的指针传递到此类中?目前我正在尝试这个。
class MouseEvent : public Event
{
public:
int testMouseData1;
int testMouseData2;
int testMouseData3;
};
class HelloWorld
{
public:
void Display(MouseEvent* evt)
{
cout << "Hello, world!" << endl;
}
};
int main(void)
{
MouseEvent* evt = new MouseEvent();
HelloWorld* world = new HelloWorld();
eventManager->RegisterEventHandler("testType", &HelloWorld::Display, world);
return 0;
}
这在 XCode 中给出了以下错误。
error: no matching function for call to '
EventManager::RegisterEventHandler(const char [9], void (HelloWorld::*)(MouseEvent*), HelloWorld*&)
'
你知道我如何安全地传递一个在其函数签名中期望派生类的指针吗?谢谢。
最佳答案
所以我找到了一个似乎对我有用的解决方案,但我不确定这样做是否完全安全。我更改了 RegisterEventHandler 方法,将发送的所有函数指针转换为同一类型...
template<typename T1, typename T2>
void RegisterEventHandler(const String& type, T1 handler, T2* obj)
{
void (T2::*evtHandler)(Event*) = (void (T2::*)(Event*)) (handler);
mCallbackList[type].push_back(boost::bind(evtHandler, obj, _1));
}
现在一切似乎都按照我最初的意图进行。但我对这一切都很陌生,所以我不完全确定这是否是安全的事情。有什么想法吗?谢谢
关于c++ - 具有接受派生类参数的基类参数的成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2213957/