【发布时间】:2012-10-20 12:14:40
【问题描述】:
我的活动管理器
对于事件管理器,我需要将许多指向函数的指针存储在向量中,以便在触发事件时调用它们。 (我会在本题末尾提供EventFunction辅助类的源码。)
// an event is defined by a string name and a number
typedef pair<string, int> EventKey;
// EventFunction holds a pointer to a listener function with or without data parameter
typedef unordered_map<EventKey, vector<EventFunction>> ListEvent;
// stores all events and their listeners
ListEvent List;
注册一个监听器可以通过调用第一个或第二个函数来完成,这取决于你是否想要接收额外的数据。 (此代码来自我的事件管理器类。)
public:
typedef void (*EventFunctionPointer)();
typedef void (*EventFunctionPointerData)(void* Data);
// let components register for events by functions with or without data parameter,
// internally simple create a EventFunction object and call the private function
void ManagerEvent::Listen(EventFunctionPointer Function, string Name, int State);
void ManagerEvent::Listen(EventFunctionPointerData Function, string Name, int State);
private:
void ManagerEvent::Listen(EventFunction Function, string Name, int State)
{
EventKey Key(Name, State);
List[Key].push_back(Function);
}
成员函数指针
该代码不起作用,因为我在我的列表中存储了函数指针而不是成员函数指针。所有这些指针都应该是成员函数指针,因为像ComponentSound 这样的组件将通过其成员函数ComponentSound::PlayerLevelup 监听事件"PlayerLevelup",以便在事件被触发时播放美妙的声音。
C++ 中的成员函数指针如下所示。
// ReturnType (Class::*MemberFunction)(Parameters);
void (ComponentSound::*PlayerLevelup)();
问题是,任何组件类都应该能够监听事件,但是在事件管理器中存储成员函数指针需要我指定监听类。正如您在示例中看到的那样,我需要指定 ComponentSound,但事件管理器应该只包含指向任何类的成员函数指针向量。
问题
回答其中一个问题会对我有很大帮助。
- 如何在事件管理器的向量中存储指向任何成员函数的函数指针? (也许所有监听函数都继承自一个抽象类
Component会有所帮助。) - 如何以其他方式设计我的事件管理器以实现目标功能? (我想对消息使用字符串和整数键。)
我试图让我的问题保持一般性,但如果您需要更多信息或代码,请发表评论。
作业
在我的成员函数指针向量中,我使用 EventFunction 而不是仅使用指针来提供两种消息类型。一个有数据参数,一个没有数据参数。
class EventFunction
{
private: EventFunctionPointer Pointer; EventFunctionPointerData PointerData; bool Data;
public:
EventFunction(EventFunctionPointer Pointer) : Pointer(Pointer), PointerData(NULL), Data(false) { }
EventFunction(EventFunctionPointerData PointerData) : PointerData(PointerData), Pointer(NULL), Data(true) { }
EventFunctionPointer GetFunction() { return Pointer; }
EventFunctionPointerData GetFunctionData() { return PointerData; } bool IsData() { return Data; }
void Call(void* Data = NULL){ if(this->Data) PointerData(Data); else Pointer(); }
};
【问题讨论】:
标签: c++ function events function-pointers