Search code examples
c++arraysc++17variadic-templates

simple way to convert parameter pack to array at compile time


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:

  • helper functions & classes with recursion: not intuitive, difficult to read and not very modern
  • C++20's std::to_array({...}): sadly it only works when all argument types are equal

what would be a clean way to implement this?


Solution

  • 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))... }; }