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

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

本文关键字:标准 C++ 初始化 何使用 常规 构造函数 模式      更新时间:2023-10-16

下面的长显式初始值设定项列表可以替换为生成它的某个模板吗?

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,如何做到这一点?

以下解决方案使用 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);

请参阅实时示例。