Search code examples
c++templatesc++17stdarray

Partial template argument deduction or workaround for std::array?


C++17 allows us to have std::array's template arguments deduced. E.g., I can write

std::array ints = { 1, 2, 3 };

and ints will be of type std::array<int, 3>.

My question is: what if I wanted to specify only the type argument of the array but have the size of the array automatically determined?

The following does not work since it seems like all template arguments have to be specified:

std::array<size_t> sizes = { 1, 2, 3 };

My compiler complains and says: 'std::array': too few template arguments.

Is it possible to have the size of the array determined automatically by template argument deduction? If not, is it possible to create an array by only specifying its type but not its size?


Solution

  • As far as I know, this cannot be done. But a helper method does the trick:

    template<typename Type, typename ... T>
    constexpr auto makeArray(T&&... t) -> std::array<Type, sizeof...(T)>
    {
        return {{std::forward<T>(t)...}};
    }
    

    Usage example:

    const auto container = makeArray<double>(-5.0, 0.0, 5.0, 10.0);