fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4.  
  5. template<typename Sig>
  6. class EventDispatcher
  7. {
  8. public:
  9. using Event = std::function<Sig>;
  10.  
  11. template<typename... Args>
  12. void Invoke(Args&& ...Params)
  13. {
  14. for (auto&& event : m_Events)
  15. {
  16. event(std::forward<Args>(Params)...);
  17. }
  18. }
  19.  
  20. void operator+=(const Event& event)
  21. {
  22. m_Events.emplace_back(event);
  23. }
  24.  
  25. private:
  26. std::vector<Event> m_Events;
  27. };
  28.  
  29. class Base
  30. {
  31. public:
  32. using eCallbacks = EventDispatcher<void(Base*)>;
  33.  
  34. eCallbacks& RenderEvent() { return m_eRenderEvent; };
  35.  
  36. void Invoke() { m_eRenderEvent.Invoke(this);}
  37.  
  38. private:
  39. eCallbacks m_eRenderEvent;
  40. };
  41.  
  42.  
  43. void Event1(Base*)
  44. {
  45. std::cout << "Event1\n";
  46. }
  47.  
  48. void Event2(Base*, int value)
  49. {
  50. std::cout << "Event2(" << value << ")\n";
  51. }
  52.  
  53. int main() {
  54.  
  55. Base base;
  56.  
  57. int IntToPass = 12345;
  58.  
  59. base.RenderEvent() += Event1;
  60. base.RenderEvent() += [=](Base* arg ) { Event2(arg, IntToPass);};
  61.  
  62.  
  63. base.Invoke();
  64. }
  65.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
Event1
Event2(12345)