Callback_18.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Callback_18.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
  2. //
  3. #include <iostream>
  4. #include <array>
  5. #include <vector>
  6. #include <map>
  7. #include <iostream>
  8. #include <functional>
  9. template<class ... Arguments>
  10. class Callback
  11. {
  12. using Function = std::function<void(Arguments ...)>;
  13. using FunctionPtr = std::shared_ptr<Function>;
  14. using Functions = std::vector<FunctionPtr>;
  15. public:
  16. FunctionPtr addListener(Function f) {
  17. FunctionPtr fp = std::make_shared<Function>(f);
  18. _functions.push_back(fp);
  19. return fp;
  20. }
  21. void removeListener(FunctionPtr fp) {
  22. _functions.erase(std::find(_functions.begin(), _functions.end(), fp));
  23. }
  24. void operator()(Arguments ... args) const {
  25. for (auto& f : _functions)
  26. f.get()->operator()(args ...);
  27. }
  28. private:
  29. Functions _functions;
  30. };
  31. class myClass {
  32. public:
  33. static void myFnct(int i) {
  34. std::cout << "test: " << i<< std::endl;
  35. };
  36. };
  37. void test(int i) {
  38. std::cout << "test: " << i << std::endl;
  39. }
  40. void test2(int i, int j) {
  41. std::cout << "test: " << i << std::endl;
  42. return;
  43. }
  44. int main()
  45. {
  46. Callback<int> callback;
  47. callback.addListener([&](int i) {
  48. std::cout << "Listener 1 -> Input is " << i << std::endl;
  49. });
  50. auto id = callback.addListener([&](int i) {
  51. std::cout << "Listener 2 -> Input is " << i << std::endl;
  52. });
  53. callback.addListener([&](int i) {
  54. std::cout << "Listener 3 -> Input is " << i << std::endl;
  55. });
  56. callback.addListener(test);
  57. callback.addListener(&myClass::myFnct);
  58. callback.removeListener(id);
  59. callback(71);
  60. }