具有结构和继承的初始化列表

initializer list with struct and inheritance

我正在使用结构的初始化列表。但是,它不适用于继承。

这段代码很好。

struct K {
int x, y;
};

K k {1, 2};

但是,这会产生错误。

struct L : public K {};
L l {1, 2};

此外,这不起作用。

struct X {
    int x;
};

struct Y : public X {
    int y;
};

Y y {1, 2};

有没有办法将初始化列表与继承的结构一起使用。我在模板中使用它们,所以如果它是继承的 class 与否,它不会编译。

Is there a way to use initializer lists with inherited structs.

如果添加具有正确参数的构造函数,则可以使用初始化列表。

struct K
{
   int x, y;
   K(int x_, y_) : x(x_), y(y_) {}
};

struct L : public K
{
   L(int x_, y_) : K(x_, y_) {}
};

K k {1, 2};
L l {1, 2};

您的代码适用于 C++17。由于 C++17 LY 都被视为 aggregate type:

no virtual, private, or protected (since C++17) base classes

则允许brace elision;即可以省略子聚合的嵌套初始化列表周围的大括号,然后您可以只写 L l {1, 2};Y y {1, 2};(而不是 L l {{1, 2}};Y y {{1}, 2};)。

If the aggregate initialization uses copy- (until C++14)list-initialization syntax (T a = {args..} or T a {args..} (since C++14)), 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.

LIVE

在 C++17 之前它不起作用,因为 list initialization 被执行,尝试使用适当的构造函数但失败了。