如何使用常规构造函数模式初始化 C++ 11 标准容器
How to initialize a C++ 11 standard container with regular constructor patterns?
下面的长显式初始值设定项列表可以替换为生成它的某个模板吗?
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_sequence
和std::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);
请参阅实时示例。
相关文章:
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 编译标准库类型
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 铸造标准::有没有回到原来的类型
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 标准库类型的赋值运算符的引用限定符
- 标准是否严格定义了该程序应该如何编译?
- 如何从Windows应用程序输出到标准?
- 安全到标准:移动会员?
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 这是否符合C++标准:双响双响,例如!!(-0.0).
- 标准::变体的赋值运算符
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 如何在 Mac 上使用 c++17 并行标准库算法?
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 并行标准::复制复杂性