Guest User

Untitled

a guest
Nov 5th, 2013
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. struct FPoint
  2. {
  3.     float x, y;
  4.     FPoint() : x(), y() {}
  5.     FPoint(float x_, float y_) : x(x_), y(y_) {}
  6. };
  7.  
  8. class Event;
  9.  
  10. class Object
  11. {
  12. public:
  13.     virtual ~Object() {}
  14.    
  15.     virtual bool Dispatch(Event& ev) { return false; }
  16. };
  17.  
  18. class Event
  19. {
  20. public:
  21.     uintptr_t type;
  22.    
  23.     bool operator()(Object& obj) { return obj.Dispatch(*this); }
  24.    
  25. private:
  26.     Event(uintptr_t type_) : type(type_) {}
  27.    
  28.     template<class T> friend class EventType;
  29. };
  30.  
  31. template<class T> uintptr_t ClassID(T * p = NULL) { (void)p; return (uintptr_t)&ClassID<T>; }
  32.  
  33. template<class T>
  34. class EventType : public Event
  35. {
  36. protected:
  37.     EventType() : Event(ClassID<T>()) {}
  38. };
  39.  
  40. class SetPoint : public EventType<SetPoint>
  41. {
  42. public:
  43.     FPoint pos;
  44. public:
  45.     SetPoint() {}
  46.     explicit SetPoint(FPoint pos_) : pos(pos_) {}
  47.     explicit SetPoint(float x, float y) : pos(x, y) {}
  48. };
  49.  
  50. class GetPoint : public EventType<GetPoint>
  51. {
  52. public:
  53.     FPoint pos;
  54. public:
  55.     GetPoint() {}
  56.    
  57.     FPoint operator()(Object& obj) { Event::operator()(obj); return pos; }
  58. };
  59.  
  60. class FPosFrame : public Object
  61. {
  62. public:
  63.     FPoint pos;
  64.    
  65. public:
  66.     virtual bool Dispatch(Event& ev) {
  67.         if (ev.type == ClassID<SetPoint>()) {
  68.             pos = static_cast<SetPoint*>(&ev)->pos;
  69.         }
  70.         else if (ev.type == ClassID<GetPoint>()) {
  71.             static_cast<GetPoint*>(&ev)->pos = pos;
  72.         }
  73.         else {
  74.             return false; // Not found
  75.         }
  76.         return true;
  77.     };
  78. };
  79.  
  80. //----------------------------------------------------------------------
  81.  
  82. int main(int, char**)
  83. {
  84.     FPosFrame fp;
  85.     bool ok = SetPoint(10, 20)(fp);
  86.     Assert(ok);
  87.     printf("%f, %f\n", fp.pos.x, fp.pos.y);
  88.     FPoint pos = GetPoint()(fp);
  89.     printf("%f, %f\n", pos.x, pos.y);
  90.    
  91.     printf("done\n");
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment