Initializing an std::array of non-default-constructible elements?(初始化非默认可构造元素的 std::array?)
问题描述
假设类型 foo_t 具有命名构造函数习惯用法 make_foo().现在,我想要正好有 123 个 foo ——不多也不少.所以,我正在考虑一个 std::array<foo_t, 123>.现在,如果 foo_t 是默认可构造的,我会写:
Suppose type foo_t with a named constructor idiom, make_foo(). Now, I want to have exactly 123 foo's - no more, no less. So, I'm thinking about an std::array<foo_t, 123>. Now, if foo_t were default-constructible, I would write:
std::array<foo_t, 123> pity_the_foos;
std::generate(
std::begin(pity_the_foos), std::end(pity_the_foos),
[]() { return make_foo(); }
);
Bob 是我的叔叔,对吧?不幸的是... foo_t 没有默认 ctor.
and Bob's my uncle, right? Unfortunately... foo_t has no default ctor.
那么我应该如何初始化我的数组呢?我是否需要使用一些可变参数模板扩展巫术?
How should I initialize my array, then? Do I need to use some variadic template expansion voodoo perhaps?
注意:如果有帮助,答案可以使用 C++11、C++14 或 C++17 中的任何内容.
Note: Answers may use anything in C++11, C++14 or C++17 if that helps at all.
推荐答案
平常.
template<size_t...Is>
std::array<foo_t, sizeof...(Is)> make_foos(std::index_sequence<Is...>) {
return { ((void)Is, make_foo())... };
}
template<size_t N>
std::array<foo_t, N> make_foos() {
return make_foos(std::make_index_sequence<N>());
}
这篇关于初始化非默认可构造元素的 std::array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:初始化非默认可构造元素的 std::array?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
