Anna_Khashper

Untitled

Oct 15th, 2020
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <tuple>
  2.  
  3. // Определение списка целых чисел времени компиляции IntList
  4. template <int ... Ints>
  5. struct IntList;
  6.  
  7. template <int H, int ... I>
  8. struct IntList <H, I...>
  9. {
  10.   static int const Head = H;
  11.   using Tail = IntList<I...>;
  12. };
  13.  
  14. template <>
  15. struct IntList <> {};
  16.  
  17. // определите метафункцию Length для вычисления длины списка
  18. template <typename TL>
  19. struct Length
  20. {
  21.   static int const value = 1 +
  22.     Length <typename TL::Tail>::value;
  23. };
  24.  
  25. template <>
  26. struct Length <IntList<>>
  27. {
  28.   static int const value = 0;
  29. };
  30.  
  31. template<int N, typename IL>
  32. struct IntCons;
  33.  
  34. template<int N, int... Ints>
  35. struct IntCons<N, IntList<Ints...>>
  36. {
  37.   using type = IntList<N, Ints...>;
  38. };
  39.  
  40. template<typename IL, int N>
  41. struct IntAdd;
  42.  
  43. template<int... Ints, int N>
  44. struct IntAdd<IntList<Ints...>, N>
  45. {
  46.   using type = IntList<Ints..., N>;
  47. };
  48.  
  49. template <int N, typename IL = IntList<>>
  50. struct Generate;
  51.  
  52. template <int N, int... Ints>
  53. struct Generate<N, IntList<Ints...>>
  54. {
  55.   using type = typename IntAdd<typename Generate<N - 1, IntList<>>::type, N - 1>::type;
  56. };
  57.  
  58. template <>
  59. struct Generate<0>
  60. {
  61.   static const int length = 0;
  62.   using type = IntList<>;
  63. };
  64.  
  65. template<typename Tf, typename ...Args>
  66. auto apply(Tf f, std::tuple<Args...> t) -> decltype(apply_f(f, t, typename Generate<sizeof ... (Args)>::type()))
  67. {
  68.   return apply_f(f, t, Generate<sizeof ... (Args)>::type());
  69. }
  70.  
  71. template<typename Tf, typename ...Args, int ...Ints>
  72. auto apply_f(Tf f, std::tuple<Args...> t, IntList<Ints...>)
  73. {
  74.   return f(std::forward<Args...>(std::get<Ints>(t)));
  75.   //return 0;
  76. }
  77.  
  78. int main()
  79. {
  80.   auto f = [](int x, double y, double z) { return x + y + z; };
  81.   auto t = std::make_tuple(30, 5.0, 1.6);  // std::tuple<int, double, double>
  82.   auto x = f(std::get<0>(t), std::get<1>(t), std::get<2>(t));
  83.   auto res = apply(f, t);                // res = 36.6
  84.   return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment