我正在尝试编写一个以通用方式进行事件(或其他)调度的类。模板参数是事件侦听器的类型、要作为参数传递的事件类型以及要在侦听器上调用的函数(成员函数)。这是类定义:
template<class L, class E, void (L::*F)(const E&)>
class Dispatcher {
public:
typedef L ListenerType;
typedef E EventType;
Dispatcher ();
virtual ~Dispatcher ();
void addListener(ListenerType* listener);
void removeListener(ListenerType* listener);
void dispatch (const EventType& event);
protected:
std::vector<ListenerType*> mListeners;
};
dispatch方法的定义:
template<class L, class E, void (L::*F)(const E&)>
void Dispatcher<L, E, F>::dispatch (const EventType& event) {
for (int i = 0; i < mListeners.size(); ++i) {
if(mListeners[i]) {
(mListeners[i]->*F)(event);
}
}
}
最后是测试用例:
struct E {
unsigned int count;
};
class A {
public:
void fun(const E& e) {
std::cout << "Count = " << e.count;
}
};
int main (int argc, char** argv) {
Dispatcher<A, E, &A::fun> disp;
A a;
E e;
e.count = 10;
disp.addListener(&a);
disp.dispatch(e);
return 0;
}
我不明白的是它按预期运行,输出“Count = 10”,但编译器指出:
..\bcore/Dispatcher.h: In instantiation of 'void ts::Dispatcher<L, E, F>::dispatch(const EventType&) [with L = A; E = E; void (L::* F)(const E&) = &A::fun; ts::Dispatcher<L, E, F>::EventType = E]':
..\main.cpp:575:19: required from here
我在这里想念什么?