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

后端 未结 7 1061
情话喂你
情话喂你 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:55

    Converting a tuple to an array without making use of recursion, including use of perfect-forwarding (useful for move-only types):

    #include 
    #include 
    #include 
    
    template
    struct indices {
        using next = indices;
    };
    
    template
    struct build_indices {
        using type = typename build_indices::type::next;
    };
    
    template<>
    struct build_indices<0> {
        using type = indices<>;
    };
    
    template
    using Bare = typename std::remove_cv::type>::type;
    
    template
    constexpr
    typename build_indices>::value>::type
    make_indices()
    { return {}; }
    
    template
    std::array<
      typename std::tuple_element<0, Bare>::type,
        std::tuple_size>::value
    >
    to_array(Tuple&& tuple, indices)
    {
        using std::get;
        return {{ get(std::forward(tuple))... }};
    }
    
    template
    auto to_array(Tuple&& tuple)
    -> decltype( to_array(std::declval(), make_indices()) )
    {
        return to_array(std::forward(tuple), make_indices());
    }
    
    int main() {
      std::tuple tup(1.5, 2.5, 4.5);
      auto arr = to_array(tup);
      for (double x : arr)
        std::cout << x << " ";
      std::cout << std::endl;
      return 0;
    }
    

提交回复
热议问题