fork(1) download
  1. #include <tuple>
  2. #include <iostream>
  3. #include <functional>
  4. #include <type_traits>
  5.  
  6.  
  7. struct foo
  8. {
  9. foo() : _value(0) { std::cout << "default foo" << std::endl; }
  10. foo(int value) : _value(value) { std::cout << "int foo" << std::endl; }
  11. foo(const foo& other) : _value(other._value) { std::cout << "copy foo" << std::endl; }
  12. foo(foo&& other) : _value(other._value) { std::cout << "move foo" << std::endl; }
  13.  
  14. int _value;
  15. };
  16.  
  17. template<int ...> struct seq {};
  18.  
  19. template<int N, int ...S> struct gens : gens<N-1, N-1, S...> {};
  20.  
  21. template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
  22.  
  23. template <typename R, typename Tp, typename ...FArgs>
  24. struct t_app_aux {
  25. template<int ...S>
  26. R static callFunc(std::function<R (FArgs...)> f, Tp&& t, seq<S...>) {
  27. return f(std::get<S>(std::forward<Tp>(t)) ...);
  28. }
  29. };
  30.  
  31. template <typename R, typename Tp, typename ...FArgs>
  32. R t_app(std::function<R (FArgs...)> f, Tp&& t)
  33. {
  34. static_assert(std::tuple_size<typename std::remove_reference<Tp>::type>::value == sizeof...(FArgs),
  35. "type error: t_app wrong arity");
  36.  
  37. return t_app_aux<R, Tp, FArgs...>::callFunc(f, std::forward<Tp>(t), typename gens<sizeof...(FArgs)>::type());
  38. }
  39.  
  40.  
  41.  
  42. int main(void)
  43. {
  44. std::cout << "Tuple creation" << std::endl;
  45. std::tuple<int, float, foo> t = std::make_tuple(1, 1.2, foo(5));
  46. std::cout << "Tuple created" << std::endl;
  47. std::function<double (int,float,foo&)> foo1 = [](int x, float y, foo& z) {
  48. return x + y + z._value;
  49. };
  50.  
  51. std::cout << "Function created" << std::endl;
  52. std::cout << t_app(foo1,t) << std::endl;
  53. std::cout << "Function applied" << std::endl;
  54. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Tuple creation
int foo
move foo
move foo
Tuple created
Function created
7.2
Function applied