Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 245
j00hi Avatar asked Jan 02 '23 10:01

j00hi


1 Answers

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);
like image 160
Benjamin Bihler Avatar answered Jan 04 '23 00:01

Benjamin Bihler