fork download
  1. #include <memory>
  2. #include <functional>
  3. #include <iostream>
  4.  
  5. struct function_wrapper
  6. {
  7. virtual ~function_wrapper() {}
  8. };
  9. template <typename... Args>
  10. struct variadic_function : function_wrapper
  11. {
  12. variadic_function(std::function<void(Args...)> f) : f_(std::move(f)) {}
  13. void operator()(Args &&... args) { f_(std::forward<Args>(args)...); }
  14.  
  15. private:
  16. std::function<void(Args...)> f_;
  17. };
  18.  
  19. class dispatcher
  20. {
  21. public:
  22. template <typename... Args>
  23. void register_event(std::function<void(Args...)> f)
  24. {
  25. f_ = std::make_shared<variadic_function<Args...>>(std::move(f));
  26. }
  27.  
  28. template <typename... Args>
  29. void post(Args &&... args)
  30. {
  31. auto f = std::dynamic_pointer_cast<variadic_function<Args...>>(f_);
  32. if (f)
  33. {
  34. (*f)(std::forward<Args>(args)...);
  35. }
  36. }
  37.  
  38. private:
  39. std::shared_ptr<function_wrapper> f_;
  40. };
  41.  
  42. int main()
  43. {
  44. dispatcher d;
  45. std::function<void(int)> f = [](int a) { std::cout << a << "\n"; };
  46. d.register_event(f);
  47. d.post(42);
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
42