fork download
  1. #include <cstddef>
  2. #include <array>
  3. #include <iostream>
  4. #include <string>
  5. #include <tuple>
  6. #include <type_traits>
  7. #include <utility>
  8.  
  9. template<typename T>
  10. auto wrap_value(T&& value)
  11. {
  12. return std::tuple<T&&>(std::forward<T>(value));
  13. }
  14.  
  15. template<typename T, std::size_t N>
  16. std::array<T, N>& wrap_value(std::array<T, N>& value)
  17. {
  18. return value;
  19. }
  20.  
  21. template<typename T, std::size_t N>
  22. std::array<T, N> const& wrap_value(std::array<T, N> const& value)
  23. {
  24. return value;
  25. }
  26.  
  27. template<typename T, std::size_t N>
  28. std::array<T, N>&& wrap_value(std::array<T, N>&& value)
  29. {
  30. return std::move(value);
  31. }
  32.  
  33. template<std::size_t... Is, typename... Ts>
  34. std::array<std::common_type_t<Ts...>, sizeof...(Is)>
  35. join_arrays_impl(std::index_sequence<Is...>, std::tuple<Ts...>&& parts)
  36. {
  37. return {std::get<Is>(std::move(parts))...};
  38. }
  39.  
  40. template<typename... Ts>
  41. auto join_arrays(Ts&&... parts)
  42. {
  43. auto wrapped_parts = std::tuple_cat((wrap_value)(std::forward<Ts>(parts))...);
  44. constexpr auto size = std::tuple_size<decltype(wrapped_parts)>::value;
  45. std::make_index_sequence<size> seq;
  46. return (join_arrays_impl)(seq, std::move(wrapped_parts));
  47. }
  48.  
  49. int main()
  50. {
  51. std::array<std::string, 2> strings = { "a", "b" };
  52. std::array<std::string, 2> more_strings = { "c", "d" };
  53. std::string another_string = "e";
  54.  
  55. auto result = join_arrays(strings, more_strings, another_string);
  56. for (auto const& i : result) {
  57. std::cout << i << '\n';
  58. }
  59.  
  60. // Making sure old strings are valid.
  61. std::cout << '\n';
  62. std::cout << strings[0] << ' ' << strings[1] << '\n';
  63. std::cout << more_strings[0] << ' ' << more_strings[1] << '\n';
  64. std::cout << another_string << '\n';
  65. }
  66.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
a
b
c
d
e

a b
c d
e