使用另一个聚合对象聚合列表初始化

Aggregate list initialization with another aggregate object

我有:

struct DisplayConfig {
    int width;
    int height;
    int colorDepth;
};

还有一个聚合:

struct DisplayResolution {
    int width;
    int height;
};

我想对我们这样的他们说:

DisplayResolution resolution{1920, 1080};
DisplayConfig config{r, 32};

这是行不通的。

DisplayConfig 更改为:

struct DisplayConfig {
    DisplayResolution resolution;
    int colorDepth;
};

会工作,但更改 DisplayConfig 不是一个选项,访问 config.width 也将不再工作。

DisplayConfig{r.width, r.height, 32}; 当然可以,但语法类似于:

DisplayConfig config{r, 32};

可能吗?

不,鉴于您的情况,这是不可能的:"changing DisplayConfig is not an option"。 class DisplayConfig 确实满足聚合条件(在 C++14 中),因为它没有用户提供的构造函数,没有私有或受保护的非静态数据成员,没有基数 classes,没有虚函数。

当通过初始化列表初始化这样的聚合时,以下内容适用:

8.5.1 Aggregates [dcl.init.aggr]
...
2 When an aggregate is initialized by an initializer list, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order. Each member is copy-initialized from the corresponding initializer-clause. If the initializer-clause is an expression and a narrowing conversion is required to convert the expression, the program is ill-formed. [ Note: If an initializer-clause is itself an initializer list, the member is list-initialized, which will result in a recursive application of the rules in this section if the member is an aggregate. —end note ]

所以在下面的语句中:

DisplayConfig config{r, 32};

r作为DisplayConfig的第一个成员width的初始值设定项。由于转换失败导致错误:

error: cannot convert 'DisplayResolution' to 'int' in initialization
     DisplayConfig config{ r, 32 };
                             ^

和一个警告,因为 DisplayConfig class 的 depth 成员没有给出初始值设定项:

warning: missing initializer for member 'DisplayConfig::colorDepth' [-Wmissing-field-initializers]