简体   繁体   English

初始化非默认可构造元素的 std::array?

[英]Initializing an std::array of non-default-constructible elements?

Suppose type foo_t with a named constructor idiom, make_foo() .假设类型foo_t具有命名构造函数, make_foo() Now, I want to have exactly 123 foo's - no more, no less.现在,我想要正好有 123 个 foo ——不多也不少。 So, I'm thinking about an std::array<foo_t, 123> .所以,我正在考虑一个std::array<foo_t, 123> Now, if foo_t were default-constructible, I would write:现在,如果foo_t是默认可构造的,我会写:

std::array<foo_t, 123> pity_the_foos;
std::generate(
    std::begin(pity_the_foos), std::end(pity_the_foos),
    []() { return make_foo(); }
);

and Bob's my uncle, right?鲍勃是我叔叔,对吧? Unfortunately... foo_t has no default ctor.不幸的是...... foo_t没有默认的ctor。

How should I initialize my array, then?那我应该如何初始化我的数组呢? Do I need to use some variadic template expansion voodoo perhaps?我是否需要使用一些可变参数模板扩展巫术?

Note: Answers may use anything in C++11, C++14 or C++17 if that helps at all.注意:如果有帮助,答案可能会使用 C++11、C++14 或 C++17 中的任何内容。

The usual.通常。

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>());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用非默认可构造类型填充std :: array(无可变参数模板) - Populate std::array with non-default-constructible type (no variadic templates) 如何初始化std :: array <T, 2> 其中T是不可复制的,非默认可构造的? - How to initialize an std::array<T, 2> where T is non-copyable and non-default-constructible? std::map emplace 不可移动不可复制非默认可构造类型 - std::map emplace non-movable non-copyable non-default-constructible type 使用一元调整大小减小非默认可构造元素的容器大小 - Decrease size of container of non-default-constructible elements using unary resize 如何正确初始化非默认可构造的类成员? - How to properly initialize non-default-constructible class member? 如何初始化不可默认构造的不可复制对象的元组? - How to initialize a tuple of non-default-constructible not-copyable objects? 移动具有非默认构造 class 保护的构造函数 - Move constructor with protection for non-default-constructible class 创建非默认可构造类的虚拟对象 - Create dummy object of non-default-constructible class 如何创建C ++ 11不可默认构造的分配器? - How to create a C++ 11 non-default-constructible allocator? 使用 Boost.Python 导出非默认可构造类 - Exporting non-default-constructible classes with Boost.Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM