fork(26) download
  1. #include <iostream>
  2. #include <tuple>
  3. #include <functional>
  4.  
  5. namespace helper
  6. {
  7. template <std::size_t... Ts>
  8. struct index {};
  9.  
  10. template <std::size_t N, std::size_t... Ts>
  11. struct gen_seq : gen_seq<N - 1, N - 1, Ts...> {};
  12.  
  13. template <std::size_t... Ts>
  14. struct gen_seq<0, Ts...> : index<Ts...> {};
  15. }
  16.  
  17. template <typename... Ts>
  18. class Action_impl
  19. {
  20. private:
  21. std::function<void (Ts...)> f;
  22. std::tuple<Ts...> args;
  23. public:
  24. template <typename F>
  25. Action_impl(F&& func, Ts&&... args)
  26. : f(std::forward<F>(func)),
  27. args(std::make_tuple(std::forward<Ts>(args)...))
  28. {}
  29.  
  30. template <typename... Args, std::size_t... Is>
  31. void func(std::tuple<Args...>& tup, helper::index<Is...>)
  32. {
  33. f(std::get<Is>(tup)...);
  34. }
  35.  
  36. template <typename... Args>
  37. void func(std::tuple<Args...>& tup)
  38. {
  39. func(tup, helper::gen_seq<sizeof...(Args)>{});
  40. }
  41.  
  42. void act()
  43. {
  44. func(args);
  45. }
  46. };
  47.  
  48. template <typename F, typename... Args>
  49. Action_impl<Args...> make_action(F&& f, Args&&... args)
  50. {
  51. return Action_impl<Args...>(std::forward<F>(f), std::forward<Args>(args)...);
  52. }
  53.  
  54. int main()
  55. {
  56. auto add = make_action([] (int a, int b) { std::cout << a+b; }, 2, 3);
  57.  
  58. add.act();
  59. }
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
5