I have been giving the following problem to solve. Make a generic Subject class (referring to Observor Pattern) such that it can accept any data type( primitive or user type). The register, remove and notify functions are also required to be customizable. As an example, we have a WeatherStation class which notifies observors on data type 'int'. It makes a DB entry on registering and removing observors.
Another example(not shown) is BroadcastHandler which notifies observors on stock exchange quotes. It makes entry in files on registering and removing observors.
I wrote the following code to implement it.
#include <iostream>
#include <set>
template <class T>
class Observor
{
public :
virtual void update(const T& t) = 0;
virtual ~Observor(){}
};
template<class T>
class Subject
{
public :
virtual void registerObservor(Observor<T>* obv) = 0;
virtual void removeObservor(Observor<T>* obv) = 0;
virtual void notifyObservors(T t);
virtual ~Subject(){}
};
template<class T>
class WeatherStation : public Subject<T>
{
public :
void registerObservor(Observor<T>* obv)
{
_observors.insert(obv);
//Make DB Entry
}
void removeObservor(Observor<T>* obv)
{
if(_observors.find(obv) != _observors.end())
{
_observors.erase(obv);
//Make DB Entry
}
}
void notifyObservors(T t)
{
for(auto itr = _observors.begin(),
itrEnd = _observors.end(); itr != itrEnd; ++itr)
{
(*itr)->update(t);
}
}
private :
std::set< Observor<T>* > _observors;
};
int main()
{
WeatherStation<int> wStation;
}
I get the following error from the linker
observor_pattern.o:observor_pattern.cpp:(.rdata$_ZTV7SubjectIiE[__ZTV7SubjectIiE]+0x10)||undefined reference to `Subject<int>::notifyObservors(int)'