c++ - Generic Subject class Observor Pattern -


i have been giving following problem solve. make generic subject class (referring observor pattern) such can accept data type( primitive or user type). register, remove , notify functions required customizable. example, have weatherstation class notifies observors on data type 'int'. makes db entry on registering , removing observors.

another example(not shown) broadcasthandler notifies observors on stock exchange quotes. makes entry in files on registering , removing observors.

i wrote following code 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 following error linker

observor_pattern.o:observor_pattern.cpp:(.rdata$_ztv7subjectiie[__ztv7subjectiie]+0x10)||undefined reference `subject<int>::notifyobservors(int)' 

indeed (as linker tells you) not have definition of subject<t>::notifyobservors(t), , did not declare =0. intentional? think proper code might be

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) = 0;                                //   ^^^   virtual ~subject(){} }; 

though better approach have observor-handling code in subject, not in weatherstation, because seems subject class about. it's subject's responsibility handle observors, , weatherstation's responsibility should data sensors, etc.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -