初始化非默认可构造元素的 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>());
}
相关文章