Guest User

Untitled

a guest
Oct 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. #ifndef __DISPATCHER_H
  2. #define __DISPATCHER_H
  3.  
  4. #include <functional>
  5. #include <list>
  6.  
  7. template <typename... Args>
  8. class Dispatcher
  9. {
  10. public:
  11. typedef std::function<void(Args...)> CBType;
  12.  
  13. class CBID
  14. {
  15. public:
  16. CBID() : valid(false) {}
  17. private:
  18. friend class Dispatcher<Args...>;
  19. CBID(typename std::list<CBType>::iterator i)
  20. : iter(i), valid(true)
  21. {}
  22.  
  23. typename std::list<CBType>::iterator iter;
  24. bool valid;
  25. };
  26.  
  27. // register to be notified
  28. CBID addCB(CBType cb)
  29. {
  30. if (cb)
  31. {
  32. cbs.push_back(cb);
  33. return CBID(--cbs.end());
  34. }
  35. return CBID();
  36. }
  37.  
  38. // unregister to be notified
  39. void delCB(CBID &id)
  40. {
  41. if (id.valid)
  42. {
  43. cbs.erase(id.iter);
  44. }
  45. }
  46.  
  47. void broadcast(Args... args)
  48. {
  49. for (auto &cb : cbs)
  50. {
  51. cb(args...);
  52. }
  53. }
  54.  
  55. private:
  56. std::list<CBType> cbs;
  57. };
  58.  
  59. #endif
Add Comment
Please, Sign In to add comment