Advertisement
MaximCherchuk

C++11

Jan 8th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. #include <tuple>
  2. #include <iostream>
  3. #include <array>
  4. #include <utility>
  5.  
  6. template<typename Array, std::size_t... I>
  7. decltype(auto) a2t_impl(const Array& a, std::index_sequence<I...>)
  8. {
  9.     return std::make_tuple(a[I]...);
  10. }
  11.  
  12. template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
  13. decltype(auto) a2t(const std::array<T, N>& a)
  14. {
  15.     return a2t_impl(a, Indices());
  16. }
  17.  
  18. template<class Ch, class Tr, class Tuple, std::size_t... Is>
  19. void print_tuple_impl(std::basic_ostream<Ch,Tr>& os,
  20.                       const Tuple & t,
  21.                       std::index_sequence<Is...>)
  22. {
  23.     using swallow = int[]; // guaranties left to right order
  24.     (void)swallow{0, (void(os << (Is == 0? "" : ", ") << std::get<Is>(t)), 0)...};
  25. }
  26.  
  27. template<class Ch, class Tr, class... Args>
  28. decltype(auto) operator<<(std::basic_ostream<Ch, Tr>& os,
  29.                           const std::tuple<Args...>& t)
  30. {
  31.     os << "(";
  32.     print_tuple_impl(os, t, std::index_sequence_for<Args...>{});
  33.     return os << ")";
  34. }
  35.  
  36. int main() {
  37.     std::array<int, 4> array = {1,2,3,4};
  38.     auto tuple = a2t(array);
  39.     static_assert(std::is_same<decltype(tuple), std::tuple<int, int, int, int>>::value, "");
  40.  
  41.     std::cout << tuple << '\n';
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement