Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 751
not-a-user Avatar asked Aug 14 '14 15:08

not-a-user


1 Answers

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.

like image 94
Constructor Avatar answered Oct 29 '22 04:10

Constructor