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

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

最佳答案

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

参见 live example .

关于c++ - 如何使用常规构造函数模式初始化 C++ 11 标准容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25312468/

相关文章:

c++ - 在 64 位系统的低地址分配内存的最可靠/可移植的方法是什么?

c++ - 创建用于构建 32 位应用程序的工具包

c++ - 替代虚拟类型定义

c++ - 什么是 move 语义?

c++ - 我如何将可调用对象传递给函数作为参数

C++ char 数组传递给函数

c++ - 为什么编译器不能(或不能)推断出 static_cast 的类型参数?

c++ - 为什么以后不能在模板函数中添加默认参数?

c++ - 'U' 不指代一个值

c++ - 我怎样才能在 C++ 中循环对