Callback_04.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <functional>
  4. #include <vector>
  5. using namespace std;
  6. class Caller {
  7. public:
  8. uint8_t age = 12;
  9. template<class T> void addCallback(T* const object, void(T::* const mf)(bool, int))
  10. {
  11. using namespace std::placeholders;
  12. callbacks_.emplace_back(std::bind(mf, object, _1, _2));
  13. }
  14. void addCallback(void(* const fun)(bool, int))
  15. {
  16. callbacks_.emplace_back(fun);
  17. }
  18. void callCallbacks(bool firstval, int secondval)
  19. {
  20. auto self = this;
  21. for (const auto& cb : callbacks_)
  22. cb(firstval, secondval);
  23. }
  24. private:
  25. std::vector<std::function<void(bool, int)>> callbacks_;
  26. };
  27. class Callee {
  28. public:
  29. void MyFunction(bool b, int i) {
  30. printf("MyRegularFunction: %d %d", b, i);
  31. }
  32. };
  33. void MyRegularFunction(bool b, int i) {
  34. printf("MyRegularFunction: %d %d", b, i);
  35. }
  36. Caller caller = Caller();
  37. Callee callee = Callee();
  38. //then, somewhere in Callee, to add the callback, given a pointer to Caller `ptr`
  39. int main(int argc, char const* argv[]) {
  40. printf("\nCompiler:%ld\n", __cplusplus);
  41. // caller.addCallback(&Callee::MyFunction);
  42. //or to add a call back to a regular function
  43. caller.addCallback(&MyRegularFunction);// Main method
  44. caller.callCallbacks(true, 12);
  45. return 0;
  46. }