Search code examples
c++arraysc++11stdarray

Initialize std::array with implied length


In C you can do int a[] = {1,2,3,4,5}, but C++11 std::array<int> a = {1,2,3,4,5} will give a "too few template parameters" compile error. Any way around this?


Solution

  • The best you can have is a make_array, something like:

    template<typename T, typename...Ts>
    constexpr std::array<T, 1 + sizeof...(Ts)> make_array(T&& head, Ts&&...tail)
    {
         return {{ std::forward<T>(head), std::forward<Ts>(tail)... }};
    }