fork download
  1. #include <functional>
  2. #include <list>
  3. #include <iostream>
  4. #include <string>
  5.  
  6.  
  7. template <class H> struct IX {
  8. virtual ~IX() {}
  9. virtual void AddHandler(H handler) = 0; };
  10.  
  11. template <class A> struct Event : IX<std::function<void(A)>> {
  12. void AddHandler(std::function<void(A)> handler) { mHandlers.push_back(std::move(handler)); }
  13. void Fire(A argument) {
  14. for(auto i = mHandlers.begin(), e = mHandlers.end(); i != e; ++i) {
  15. std::function<void(A)> & handler(*i);
  16. if(handler) {
  17. handler(argument);
  18. }
  19. }
  20. }
  21. private:
  22. std::list<std::function<void(A)>> mHandlers; };
  23.  
  24. struct SomeSender {
  25. SomeSender(std::string const & name) : mName(name) { }
  26. IX<std::function<void(std::string const &)>> & OnNameChanged(void) { return mOnNameChanged; }
  27. void ChangeName(std::string const & name) { mName = name; mOnNameChanged.Fire(mName); }
  28. private:
  29. Event<std::string const &> mOnNameChanged;
  30. std::string mName;
  31. };
  32.  
  33.  
  34.  
  35. int main(void) {
  36. SomeSender ss("Bob");
  37. ss.OnNameChanged().AddHandler([](std::string const & name) {
  38. std::cout << name << "!" << std::endl;
  39. });
  40. ss.OnNameChanged().AddHandler([](std::string const & name) {
  41. std::cout << name << "?" << std::endl;
  42. });
  43. ss.ChangeName("Alice");
  44. // ss.OnNameChanged().Fire("hoge");
  45. std::getchar();
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 3024KB
stdin
Standard input is empty
stdout
Alice!
Alice?