fork(3) download
  1. #include <iostream>
  2. #include <functional>
  3. #include <vector>
  4.  
  5. template <typename T>
  6. class Event
  7. {
  8. public:
  9. using func = std::function<void(T)>;
  10.  
  11.  
  12. void Raise(T arg)
  13. {
  14. for (auto handler : _handlers)
  15. {
  16. handler(arg);
  17. }
  18. }
  19.  
  20. void operator ()(T arg)
  21. {
  22. Raise(arg);
  23. }
  24.  
  25. Event& operator += (func f)
  26. {
  27. _handlers.push_back(f);
  28. return *this;
  29. }
  30.  
  31. Event& operator -= (func f)
  32. {
  33. for (auto handler : _handlers)
  34. {
  35.  
  36. if (handler.template target<void(T)>() == f.template target<void(T)>())
  37. {
  38. _handlers.erase(handler);
  39. break;
  40. }
  41. }
  42.  
  43. return *this;
  44. }
  45.  
  46. private:
  47. std::vector<func> _handlers;
  48. };
  49.  
  50. class SomeClass
  51. {
  52. public:
  53. Event<std::string> SomethingChanged;
  54. };
  55.  
  56. class Onemoreclass
  57. {
  58. SomeClass _someClass{};
  59. public:
  60. Onemoreclass()
  61. {
  62. _someClass.SomethingChanged += std::bind(&Onemoreclass::Print, *this, std::placeholders::_1);
  63. }
  64.  
  65. private:
  66. void Print(std::string message) {std::cout << message << std::endl; }
  67. };
  68.  
  69. int main() {
  70. // your code goes here
  71. Onemoreclass one;
  72.  
  73. return 0;
  74. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty