is there a simple way to create an std::array
from a parameter pack at compile time?
constexpr auto array = to_array<int>(1, 2, 3, 'a', 5.5f);
there are existing solutions:
std::to_array({...})
: sadly it only works when all argument types are equalwhat would be a clean way to implement this?
What about simply
template <typename T, typename... Args>
constexpr std::array<T, sizeof...(Args)> to_array (Args && ... args)
{ return {{ std::forward<Args>(args)... }}; }
?
Or, maybe, if you want to add the static_cast
template <typename T, typename... Args>
constexpr std::array<T, sizeof...(Args)> to_array (Args && ... args)
{ return {{ static_cast<T>(std::forward<Args>(args))... }}; }
and using CTAD and auto
return placeholder, you can reduce a little the typewriting
template <typename T, typename... Args>
constexpr auto to_array (Args && ... args)
{ return std::array{ static_cast<T>(std::forward<Args>(args))... }; }