How to initialize a standard C ++ 11 container with regular constructor templates?

Is it possible to replace a long explicit list of initializers with the following 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 this code only works because we have constexpr int n_foos = 8 . How can this be done for arbitrary and large n_foos ?

+6
source share
1 answer

The following solution uses C ++ 14 std::index_sequence and std::make_index_sequence (which can be easily implemented in the 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 a live example .

+8
source

Source: https://habr.com/ru/post/973829/


All Articles