Callback_15.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <array>
  2. #include <vector>
  3. #include <map>
  4. #include <iostream>
  5. #include <functional>
  6. template<class ... Arguments>
  7. class Callback
  8. {
  9. using Function = std::function<void(Arguments ...)>;
  10. using FunctionPtr = std::shared_ptr<Function>;
  11. using Functions = std::vector<FunctionPtr>;
  12. public:
  13. FunctionPtr addListener(Function f) {
  14. FunctionPtr fp = std::make_shared<Function>(f);
  15. _functions.push_back(fp);
  16. return fp;
  17. }
  18. void removeListener(FunctionPtr fp) {
  19. _functions.erase(std::find(_functions.begin(), _functions.end(), fp));
  20. }
  21. void operator()(Arguments ... args) const {
  22. for (auto& f : _functions)
  23. f.get()->operator()(args ...);
  24. }
  25. private:
  26. Functions _functions;
  27. };
  28. void test(int i) {
  29. std::cout << "test: " << i << std::endl;
  30. }
  31. int main()
  32. {
  33. Callback<int> callback;
  34. callback.addListener([](int i) {
  35. std::cout << "Listener 1 -> Input is " << i << std::endl;
  36. });
  37. auto id = callback.addListener([](int i) {
  38. std::cout << "Listener 2 -> Input is " << i << std::endl;
  39. });
  40. callback.addListener([](int i) {
  41. std::cout << "Listener 3 -> Input is " << i << std::endl;
  42. });
  43. callback.addListener(test);
  44. callback.removeListener(id);
  45. callback(71);
  46. }