c++ - 具有嵌套初始化列表的子对象 std::array 的聚合初始化

标签 c++ initialization initializer-list initializer stdarray

使用嵌套花括号初始化器列表初始化聚合类型(例如 std::array)及其子对象的正确方法是什么?我不想直接调用子类型的构造函数。

这是一个反复出现的问题,我总是很惊讶下面的代码不起作用,因为元素的类型是指定的,因此编译器可以推导出正确的构造函数。

请注意,示例类型 A 不一定是聚合(但当然它必须支持花括号初始化列表)。

#include <array>    

struct A
{
    int values[4];
};

int main()
{
    std::array<A, 2> arr{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }};

    // Works only if A is an aggregate, also looks confusing, I don't want to do this
    //std::array<A, 2> arr{ 0, 1, 2, 3, 4, 5, 6, 7 };

    // I don't want to do this neither
    //std::array<A, 2> arr{A{ 0, 1, 2, 3 }, A{ 4, 5, 6, 7 }};

    return 0;
}

但我得到的只是错误

error: too many initializers for 'std::array<A, 2ul>'

最佳答案

您可以在子对象的初始化周围添加大括号,例如

std::array<A, 2> arr{{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }}};

std::array<A, 2> arr{{ 0, 1, 2, 3 }, { 4, 5, 6, 7 }};不起作用,因为 brace elision ,

the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.

请注意,第一个初始化子句 { 0, 1, 2, 3 }可用于初始化 std::array 的整个内部数组(剩余元素将被初始化为零)。然后{ 4, 5, 6, 7}成为超额条款。

关于c++ - 具有嵌套初始化列表的子对象 std::array 的聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40112072/

相关文章:

c++ - 嵌套初始化列表的构造函数

c++ - 智能指针与初始值设定项列表混淆

c++ - 强制接口(interface)的模板

c++ - 如何将常量数组传递给构造函数初始化列表

c++ - 关于使用 boost::zip 迭代器的一些代码的问题

java - 初始化单链表 Java

Objective-C 初始化(静态方法)调用了不止一次?

c++ - 如何编写嵌套的 Initialiser 列表,例如 QPairs 的 QVector

c++ - 具有自定义返回类型和 "false"返回条件的函数?

c++ - 与 const_cast 相反