嵌套的指定初始化器

Nested designated initializers

C++ 20 是否允许嵌套的指定初始化器?例如:

struct Outer {
  int32_t counter;
  struct {
    std::string name;
  } inner;

  struct {
    std::optional<int32_t> value;
  } inner_optional;
};

Outer outer = {
    .counter = 100,
    .inner = {
        .name = "test" // nested
    }
};

如果允许,有人可以向可信来源提供 link 吗?我在 cppreference 上找不到它。

是的,显示的程序格式正确。

适用于最外层初始化器的相同规则适用于内部初始化器。最外层的初始化器对于指定的初始化器来说并不特殊。

是的,支持,cppreference - aggregate initialization 状态:

If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member/public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive.

列表初始化是聚合的聚合初始化。

请注意,C++ 不支持真正嵌套的 C 指定初始化器,即 outer = {.inner.name = ""};。所需的解决方法正是您所写的。