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