我试图用C ++理解观察者模式。 我基本上是在尝试使用模板来编写一个简单的程序来理解它,我必须承认我不是那个用模板编程的诗句,因为它我无法解决这个编译错误。如果有人能请点,那会很棒出于我做错了什么
#include<iostream>
#include<conio.h>
#include<list>
#include<Windows.h>
using namespace std;
template <class T>
class IEventListener
{
public:
virtual ~IEventListener() {}
virtual void onEvent(T eventData) = 0;
};
template <class T>
class EventGenerator
{
public:
EventGenerator(){}
virtual ~EventGenerator() {}
void addListener(IEventListener<T> l)
{
listeners.push_back(l);
}
void trigger(T eventData)
{
for (auto it = listeners.begin(); it != listeners.end(); ++it)
{
(*it).onEvent(eventData);
}
}
private:
std::list<IEventListener<T>> listeners;
};
class IntListener : public IEventListener<int>
{
public:
//event callback
virtual void onEvent(int eventData)
{
std::cout << "int" <<eventData<< std::endl;
}
};
class ActualIntEventGenerator : public EventGenerator<int>
{
public:
void firstMethod()
{
int a = 10;
trigger(a);
}
};
void main()
{
IntListener i;
ActualIntEventGenerator intGenerator;
intGenerator.addListener(i);
Sleep(5000);
}
我得到的错误是
error C2259: 'IEventListener<int>' :
cannot instantiate abstract class due to following members:
void IEventListener<int>::onEvent(T)' : is abstract with [T=int]
提前致谢