Callback_09.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <iostream>
  2. #include <string>
  3. #include "dispatcher.hpp" // the implementation is here
  4. using namespace std;
  5. // a dummy enum for this example
  6. enum EventEnum { EVENT1, EVENT2, EVENT3 };
  7. // template <class T>
  8. void myCb(string str, EventEnum evt) {
  9. cout << "myCb: " << str << " got event " << evt << endl;
  10. }
  11. int main(int argc, char* argv[])
  12. {
  13. // 2 example dispatchers, any number of arguments and types can be used:
  14. Dispatcher<string, EventEnum> d1;// here any cb(string, EventEnum) can register
  15. Dispatcher<int, long, double> d2;// here any cb(int, long, double) can register
  16. // From the "most simple" lambda usage example ...
  17. auto cbid1 = d1.addCB([](string str, EventEnum evt) {
  18. cout << "CB1:" << str << " got event " << evt << endl;
  19. });
  20. auto cbid2 = d1.addCB([](string str, EventEnum evt) {
  21. cout << "CB2:" << str << " got event " << evt << endl;
  22. });
  23. auto cbid3 = d1.addCB(&myCb);
  24. d1.broadcast("** Dispatching to 2 is **", EVENT1);
  25. d1.broadcast("** E a s y **", EVENT2);
  26. d1.delCB(cbid1); // remove the first callback
  27. d1.broadcast("** Dispatching to 1 is **", EVENT1);
  28. d1.broadcast("** E a s y **", EVENT2);
  29. d1.delCB(cbid2); // remove the second callback
  30. d1.broadcast("** No one will see this **", EVENT3);
  31. // ... to the "most complex" **live** instance (not copy) usage example:
  32. class MyClassWithMethod {
  33. public:
  34. void registerCB(Dispatcher<int, long, double>& dispatcher) {
  35. using namespace std::placeholders;
  36. dispatcher.addCB(std::bind(&MyClassWithMethod::listener, this, _1, _2, _3));
  37. }
  38. private:
  39. // any method with the right signature can be used:
  40. void listener(int i, long l, double d) {
  41. cout << "listener() for " << this << ", got: " <<
  42. i << ", " << l << ", " << d << endl;
  43. }
  44. };
  45. MyClassWithMethod instance1;
  46. MyClassWithMethod instance2;
  47. instance1.registerCB(d2);
  48. instance2.registerCB(d2);
  49. d2.broadcast(65000, 12345678910, 3.14159265);
  50. d2.broadcast(56000, 1987654321, 14159265.3);
  51. return 0;
  52. }