fork(2) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. #include <functional>
  5.  
  6. class EventManager
  7. {
  8. public:
  9. template<class F>
  10. void AddClient(const F& receiver)
  11. {
  12. clients.emplace_back(new EventClient<F>(receiver));
  13. }
  14.  
  15. void Emit()
  16. {
  17. for (const auto& client : clients)
  18. {
  19. client->Respond();
  20. }
  21. }
  22.  
  23. private:
  24. struct IEventClient {
  25. virtual ~IEventClient(){}
  26. virtual void Respond() = 0;
  27. };
  28.  
  29. template<class F>
  30. struct EventClient : IEventClient
  31. {
  32. const F& f;
  33. EventClient(const F& f) : f(f){}
  34. void Respond() override { f(); }
  35. };
  36.  
  37. std::vector<std::unique_ptr<IEventClient>> clients;
  38. };
  39.  
  40. struct Foo
  41. {
  42. void operator()() const { std::cout << "I'm a Foo!\n"; }
  43. };
  44.  
  45.  
  46. int main() {
  47. EventManager eventMan;
  48.  
  49. eventMan.AddClient([]{ std::cout << "yo\n"; });
  50.  
  51. std::function<void()> f = []{ std::cout << "I'm a std function!\n"; };
  52. eventMan.AddClient(f);
  53.  
  54. eventMan.AddClient(Foo());
  55.  
  56. eventMan.Emit();
  57. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
yo
I'm a std function!
I'm a Foo!