我正在使用 C++ 中的一个事件守护程序,我想使用成员函数回调。基本上,事件队列将收集守护程序持续服务的事件。有一个带有 ID 的基类 Event 结构,所有事件都将从它派生。我希望为每个事件注册的方法在其签名中使用派生事件类型。
struct Event
{
unsigned int eventId;
};
struct EventA : public Event
{
unsigned int x;
unsigned int y;
};
// and struct EventB, EventC (use your imagination...)
const unsigned int EVENT_A = 1;
const unsigned int EVENT_B = 2;
const unsigned int EVENT_C = 3;
class Foo
{
public:
void handlerMethod_A(const EventA& e);
void handlerMethod_B(const EventB& e);
};
class Bar
{
public:
void handlerMethod_C(const EventC& e);
};
然后守护进程将允许这些类使用它们的“this”指针订阅它们的成员函数。
class EventDaemon
{
public:
void serviceEvents();
template <class CallbackClass, class EventType>
void subscribe(
const unsigned int eventId,
CallbackClass* classInstancePtr,
void (CallbackClass::*funcPtr)(EventType));
private:
Queue<Event*> eventQueue_;
};
所以在这门课之外你可以做类似的事情:
EventDaemon* ed = new EventDaemon();
Foo* foo = new Foo();
Bar* bar = new Bar();
ed->subscribe(EVENT_A, foo, Foo::handlerMethod_A);
ed->subscribe(EVENT_B, foo, Foo::handlerMethod_B);
ed->subscribe(EVENT_C, bar, Bar::handlerMethod_C);
并且 EventDaemon 循环将沿着
void EventDaemon::serviceEvents()
{
while (true)
{
if (eventQueue_.empty())
{
// yield to other threads
}
else
{
// pop an event out of the FIFO queue
Event e* = eventQueue_.pop();
// somehow look up the callback info and use it
classInstancePtr->*funcPtr(reinterpret_cast<?*>(e));
}
}
}
所以我的问题是如何按事件 ID 将“this”指针和成员函数指针存储在某种数组中。这样我就可以通过使用 e->eventId 和事件类型来查找 'classInstancePtr' 和 'funcPtr' 以及 reinterpret cast。