I am writing a very simple implementation of Observer pattern in C++. Because I want my Publisher to notify its subscribers with events that are different (e.g. not just a string, but a specific class), I have decided to use templates. My code is compiling fine, except that part that I don't know where to store all these Observers. If I use and std::list or std::vector, they will not allow to store specialized data, because their elements have to be the same. So my question is, how do I store all those observers in my Publisher class. Here is my code:
Observer.hpp
#ifndef H_OBSERVER
#define H_OBSERVER
#include <memory>
class Publisher;
template <class T>
class Observer
{
protected:
virtual void Notify(std::shared_ptr<Publisher> source, T info) = 0;
};
#endif
Publisher.hpp
#ifndef H_PUBLISHER
#define H_PUBLISHER
#include "Observer.hpp"
#include <list>
#include <string>
#include <memory>
class Publisher
{
public:
template<class T>
void NotifyObservers();
template <class T>
void AddObserver(std::shared_ptr<Observer<T>> &obs);
template <class T>
void RemoveObserver(std::shared_ptr<Observer<T>> &obs);
protected:
//std::list<std::shared_ptr<Observer> m_observers;
};
#endif