我正在處理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));
}
}
}
的線,所以我的問題是我怎麼可以存儲'this'指針和成員函數通過事件ID指向某種數組。這樣我可以通過使用e-> eventId和事件類型來查找'classInstancePtr'和'funcPtr',以及重新解析轉換。
看起來像boost函數也是模板化的,當我試圖根據任意訂閱存儲它們的數組時,我認爲它們不會起作用。我對成員函數指針有相當好的理解並使用它們,只是沒有嘗試允許從Event派生的任何參數。 – Nick
我明白你的意思了,現在我想......我使用我想象的類似於Boost函數的工作原理髮布了我的解決方案。 – Nick