Advertisement
runewalsh

[xynta] template notification

Mar 7th, 2013
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.53 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. class Notify
  7. {
  8. public:
  9.     string msg;
  10.     Notify(const string& newMsg) : msg(newMsg) {}
  11. };
  12.  
  13. class NotifyA : public Notify
  14. {
  15. public:
  16.     NotifyA(const string& newMsg) : Notify(newMsg) {}
  17. };
  18.  
  19. class NotifyB : public Notify
  20. {
  21. public:
  22.     int n;
  23.     NotifyB(const string& newMsg, int newN) : Notify(msg), n(newN) {}
  24. };
  25.  
  26. class Object
  27. {
  28. public:
  29.     virtual ~Object() {}
  30. };
  31.  
  32. template <class T>
  33. class Notifiable
  34. {
  35. public:
  36.     virtual void Notify(const T& msg) = 0;
  37. };
  38.  
  39. class Foo : public Object, public Notifiable<NotifyA>
  40. {
  41. public:
  42.     void Notify(const NotifyA& msg) override
  43.     {
  44.         printf("Foo notified about NotifyA: \"%s\"\n", msg.msg.c_str());
  45.     }
  46. };
  47.  
  48. class Bar : public Object, public Notifiable<NotifyA>, public Notifiable<NotifyB>
  49. {
  50. public:
  51.     void Notify(const NotifyA& msg) override
  52.     {
  53.         printf("Bar notified about NotifyA: \"%s\"\n", msg.msg.c_str());
  54.     }
  55.  
  56.     void Notify(const NotifyB& msg) override
  57.     {
  58.         printf("Bar notified about NotifyB: \"%s\", n = %i\n", msg.msg.c_str(), msg.n);
  59.     }
  60. };
  61.  
  62. template<class T>
  63. void send(Object* receiver, T& msg)
  64. {
  65.     Notifiable<T>* recv = dynamic_cast<Notifiable<T>*>(receiver);
  66.     if (recv)
  67.         recv->Notify(msg);
  68. }
  69.  
  70. int _tmain(int argc, _TCHAR* argv[])
  71. {
  72.     Foo foo;
  73.     Bar bar;
  74.     vector<Object*> list;
  75.     list.push_back(&foo);
  76.     list.push_back(&bar);
  77.  
  78.     send(list[0], NotifyA("hello"));
  79.     send(list[0], NotifyB("deus", 25));
  80.     send(list[1], NotifyA("world"));
  81.     send(list[1], NotifyB("machina", 36));
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement