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

时间:2014-08-14 15:56:55

标签: c++ templates c++11 initializer

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

std::array<Foo, n_foos> foos = {{
        {0, bar},
        {1, bar},
        {2, bar},
        {3, bar},
        {4, bar},
        {5, bar},
        {6, bar},
        {7, bar},
}};

现在,此代码仅适用于constexpr int n_foos = 8。如何对任意和大n_foos

进行此操作

1 个答案:

答案 0 :(得分:8)

以下解决方案使用C ++ 14 std::index_sequencestd::make_index_sequencecan 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);

请参阅live example