The desired behaviour is that of emplace
called N
times.
Very similar to this question Initializing a std::array with a constant value. Except instead of calling the copy constructor given some T
, you are given some argument list for which you call the corresponding constructor of T
.
Pseudo code:
template <typename ...Args>
std::array<T, N> create_array(Args&&... args)
{
return { T(args...), T(args...), .... };
}
For example, this is necessary when T
has members that are (smart) pointers and you want these pointers to reference unique objects.
Jarod commented that this should be implemented with a generator taking the index, and with c++20 templated lambdas we can do away with the helper function
template <std::size_t N, typename Generator>
auto make_array(Generator gen)
{
return [&]<std::size_t... I>(std::index_sequence<I...>) -> std::array<std::decay_t<decltype(gen(std::size_t{}))>, N>
{
return { {(gen(I))...} };
}(std::make_integer_sequence<std::size_t, N>{});
}