Can the long explicit initializer list in the following be replaced by some template that generates it?
std::array<Foo, n_foos> foos = {{
{0, bar},
{1, bar},
{2, bar},
{3, bar},
{4, bar},
{5, bar},
{6, bar},
{7, bar},
}};
Now here this code works only because we have constexpr int n_foos = 8
. How can this be done for arbitrary and large n_foos
?
The following solution uses C++14 std::index_sequence
and std::make_index_sequence
(which can be easily implemented in C++11 program):
template <std::size_t... indices>
constexpr std::array<Foo, sizeof...(indices)>
CreateArrayOfFoo(const Bar& bar, std::index_sequence<indices...>)
{
return {{{indices, bar}...}};
}
template <std::size_t N>
constexpr std::array<Foo, N> CreateArrayOfFoo(const Bar& bar)
{
return CreateArrayOfFoo(bar, std::make_index_sequence<N>());
}
// ...
constexpr std::size_t n_foos = 8;
constexpr auto foos = CreateArrayOfFoo<n_foos>(bar);
See live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With