If I have std::tuple (where the type is homogeneous), is there a stock function or constructor to convert to std::array
Even if title says C++11 I think C++14 solution is worth sharing (since everyone searching for problem will come up here anyway). This one can be used in compile time (constexpr proper) and much shorter than other solutions.
#include
#include
#include
#include
// Convert tuple into a array implementation
template
constexpr decltype(auto) t2a_impl(const Tuple& a, std::index_sequence)
{
return std::array{std::get(a)...};
}
// Convert tuple into a array
template
constexpr decltype(auto) t2a(const std::tuple& a)
{
using Tuple = std::tuple;
constexpr auto N = sizeof...(T) + 1;
return t2a_impl(a, std::make_index_sequence());
}
int main()
{
constexpr auto tuple = std::make_tuple(-1.3,2.1,3.5);
constexpr auto array = t2a(tuple);
static_assert(array.size() == 3, "err");
for(auto k : array)
std::cout << k << ' ';
return 0;
}
Example