Callback_10.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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(T &ccb, 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. #if 1
  18. auto cbid1 = d1.addCB([](string str, EventEnum evt) {
  19. cout << "CB1:" << str << " got event " << evt << endl;
  20. });
  21. auto cbid2 = d1.addCB([](string str, EventEnum evt) {
  22. cout << "CB2:" << str << " got event " << evt << endl;
  23. });
  24. #endif
  25. auto cbid3 = d1.addCB(&myCb);
  26. d1.broadcast("** Dispatching to 2 is **", EVENT1);
  27. d1.broadcast("** E a s y **", EVENT2);
  28. d1.delCB(cbid1); // remove the first callback
  29. d1.broadcast("** Dispatching to 1 is **", EVENT1);
  30. d1.broadcast("** E a s y **", EVENT2);
  31. d1.delCB(cbid2); // remove the second callback
  32. d1.broadcast("** No one will see this **", EVENT3);
  33. // ... to the "most complex" **live** instance (not copy) usage example:
  34. class MyClassWithMethod {
  35. public:
  36. void registerCB(Dispatcher<int, long, double>& dispatcher) {
  37. using namespace std::placeholders;
  38. dispatcher.addCB(std::bind(&MyClassWithMethod::listener, this, _1, _2, _3));
  39. }
  40. private:
  41. // any method with the right signature can be used:
  42. void listener(int i, long l, double d) {
  43. cout << "listener() for " << this << ", got: " <<
  44. i << ", " << l << ", " << d << endl;
  45. }
  46. };
  47. MyClassWithMethod instance1;
  48. MyClassWithMethod instance2;
  49. instance1.registerCB(d2);
  50. instance2.registerCB(d2);
  51. d2.broadcast(65000, 12345678910, 3.14159265);
  52. d2.broadcast(56000, 1987654321, 14159265.3);
  53. return 0;
  54. }