fork download
  1. #include <iostream>
  2. #include <list>
  3.  
  4. namespace _detailEventSystem
  5. {
  6. template<typename ... Args>
  7. class BaseFunc
  8. {
  9. public:
  10. virtual ~BaseFunc() = default;
  11. virtual void operator()(Args ...) = 0;
  12. };
  13.  
  14. template<class Type, typename ... Args>
  15. class MethodFunc final : public BaseFunc<Args...>
  16. {
  17. public:
  18. typedef void(Type::*Func)(Args ...);
  19.  
  20. MethodFunc(Type *t, Func f) : m_t(t), m_f(f) {}
  21.  
  22. void operator()(Args ...args) final { (m_t->*m_f)(args ...); }
  23. private:
  24. Type *m_t;
  25. Func m_f;
  26. };
  27.  
  28. template<typename ... Args>
  29. struct Data
  30. {
  31. BaseFunc<Args...> *event = nullptr;
  32. bool active = false;
  33. };
  34.  
  35. } // namespace _detailEventSystem
  36.  
  37. class EventListener
  38. {
  39. public:
  40. virtual ~EventListener()
  41. {
  42. if (m_reg) *m_reg = false; m_reg = nullptr;
  43. }
  44.  
  45. void _register_(bool &reg)
  46. {
  47. m_reg = &reg;
  48. }
  49. private:
  50. bool *m_reg = nullptr;
  51. };
  52.  
  53. template<typename ... Args>
  54. class EventSignal
  55. {
  56. public:
  57. template<class Type>
  58. void Connect(Type *t, void(Type::*f)(Args ...))
  59. {
  60. _detailEventSystem::Data<Args...> d = {
  61. new _detailEventSystem::MethodFunc<Type, Args ...>(t, f),
  62. true
  63. };
  64. m_lists.emplace_back(d);
  65.  
  66. auto &it = m_lists.back();
  67. t->_register_(it.active);
  68. }
  69.  
  70. void operator()(Args ...args) noexcept
  71. {
  72. for (auto i = m_lists.begin(); i != m_lists.end();)
  73. {
  74. if ((*i).active)
  75. {
  76. (*(*i).event)(args...);
  77. ++i;
  78. }
  79. else
  80. {
  81. delete (*i).event;
  82. i = m_lists.erase(i);
  83. }
  84. }
  85. }
  86.  
  87. private:
  88. using eventData = _detailEventSystem::Data<Args...>;
  89. std::list<eventData> m_lists;
  90. };
  91.  
  92. class FooB1 : public EventListener
  93. {
  94. public:
  95. ~FooB1() { delete i; i = 0; }
  96. void Key(uint32_t key, bool press)
  97. {
  98. std::cout << "hell1" << key << *i << std::endl;
  99. }
  100.  
  101. int *i = new int(10);
  102. };
  103.  
  104. int main() {
  105. FooB1 *f1 = new FooB1;
  106. EventSignal<uint32_t, bool> sig3;
  107. sig3.Connect(f1, &FooB1::Key);
  108. sig3(10, true);
  109. sig3(20, true);
  110. delete f1; f1 = nullptr;
  111. sig3(30, true);
  112.  
  113. return 0;
  114. }
Success #stdin #stdout 0s 4256KB
stdin
Standard input is empty
stdout
hell11010
hell12010