Convert std::tuple to std::array C++11

后端 未结 7 1023
情话喂你
情话喂你 2020-11-27 17:00

If I have std::tuple (where the type is homogeneous), is there a stock function or constructor to convert to std::array

相关标签:
7条回答
  • 2020-11-27 17:59

    You can do it non-recursively:

    #include <array>
    #include <tuple>
    #include <redi/index_tuple.h>  // see below
    
    template<typename T, typename... U>
      using Array = std::array<T, 1+sizeof...(U)>;
    
    template<typename T, typename... U, unsigned... I>
      inline Array<T, U...>
      tuple_to_array2(const std::tuple<T, U...>& t, redi::index_tuple<I...>)
      {
        return Array<T, U...>{ std::get<I>(t)... };
      }
    
    template<typename T, typename... U>
      inline Array<T, U...>
      tuple_to_array(const std::tuple<T, U...>& t)
      {
        using IndexTuple = typename redi::make_index_tuple<1+sizeof...(U)>::type;
        return tuple_to_array2(t, IndexTuple());
      }
    

    See https://gitlab.com/redistd/redistd/blob/master/include/redi/index_tuple.h for my implementation of index_tuple, something like that is useful for working with tuples and similar variadic templates. A similar utility was standardised as std::index_sequence in C++14 (see index_seq.h for a standalone C++11 implementation).

    0 讨论(0)
提交回复
热议问题