如何使用常规构造函数模式初始化C++ 11标准容器?

not*_*ser 6 c++ templates initializer c++11

下面的长显式初始化列表是否可以被生成它的某个模板替换?

std::array<Foo, n_foos> foos = {{
        {0, bar},
        {1, bar},
        {2, bar},
        {3, bar},
        {4, bar},
        {5, bar},
        {6, bar},
        {7, bar},
}};
Run Code Online (Sandbox Code Playgroud)

现在这里的代码只是因为我们有了constexpr int n_foos = 8.怎么能做到任意和大n_foos

Con*_*tor 8

以下解决方案使用C++ 14 std::index_sequencestd::make_index_sequence(可以在C++ 11程序中轻松实现):

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);
Run Code Online (Sandbox Code Playgroud)

查看实例.