Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <string>
- #include <vector>
- using namespace std;
- class Notify
- {
- public:
- string msg;
- Notify(const string& newMsg) : msg(newMsg) {}
- };
- class NotifyA : public Notify
- {
- public:
- NotifyA(const string& newMsg) : Notify(newMsg) {}
- };
- class NotifyB : public Notify
- {
- public:
- int n;
- NotifyB(const string& newMsg, int newN) : Notify(msg), n(newN) {}
- };
- class Object
- {
- public:
- virtual ~Object() {}
- };
- template <class T>
- class Notifiable
- {
- public:
- virtual void Notify(const T& msg) = 0;
- };
- class Foo : public Object, public Notifiable<NotifyA>
- {
- public:
- void Notify(const NotifyA& msg) override
- {
- printf("Foo notified about NotifyA: \"%s\"\n", msg.msg.c_str());
- }
- };
- class Bar : public Object, public Notifiable<NotifyA>, public Notifiable<NotifyB>
- {
- public:
- void Notify(const NotifyA& msg) override
- {
- printf("Bar notified about NotifyA: \"%s\"\n", msg.msg.c_str());
- }
- void Notify(const NotifyB& msg) override
- {
- printf("Bar notified about NotifyB: \"%s\", n = %i\n", msg.msg.c_str(), msg.n);
- }
- };
- template<class T>
- void send(Object* receiver, T& msg)
- {
- Notifiable<T>* recv = dynamic_cast<Notifiable<T>*>(receiver);
- if (recv)
- recv->Notify(msg);
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- Foo foo;
- Bar bar;
- vector<Object*> list;
- list.push_back(&foo);
- list.push_back(&bar);
- send(list[0], NotifyA("hello"));
- send(list[0], NotifyB("deus", 25));
- send(list[1], NotifyA("world"));
- send(list[1], NotifyB("machina", 36));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement