使用指定初始化器初始化基+派生类

时间:2021-07-10 20:28:56

标签: c++ c++20

考虑我们使用一个结构来列出一长串带有默认值的“初始化”值:

struct A {
  int const a = 1;
  int const b = 2;
  // long list follows...
};

然后,从 C++20 开始,可以使用指定的初始化简单地覆盖一些值,

A a = {
  .b = 3
};

但是,现在我想扩展它以用于派生的类 来自使用 A 进行初始化的类。我的新“初始化”结构 看起来像这样:

struct B : A {
  int const c = 3;
  int const d = 4;
};

但是任何初始化它的尝试都失败了!

例如

struct A {
  int const a = 1;
  int const b = 2;
};

struct B : A {
  int const c = 3;
  int const d = 4;
};

int main()
{
  [[maybe_unused]] B b =
  {
    { .a = 10 },
      .d = 42
  };
}

用 clang 编译,但给出警告:

prog.cc:18:7: warning: mixture of designated and non-designated initializers in the same initializer list is a C99 extension [-Wc99-designator]
      .d = 42
      ^~~~~~~
prog.cc:17:5: note: first non-designated initializer is here
    { .a = 10 },
    ^~~~~~~~~~~
1 warning generated.

它没有用g++编译,导致错误:

prog.cc:18:7: error: either all initializer clauses should be designated or none of them should be
   18 |       .d = 42
      |       ^

https://wandbox.org/permlink/Fmhudd24PZd381mR

我怎样才能做到这一点?

请注意,Designated initializers in C++20 中给出的答案并未提供“我如何(最好)实现这一目标?”的答案。由于给出的答案混合使用了指定和非指定初始化器,这是不允许的。

相反,我正在寻找一种解决方案,我可以在其中构造 B 类型的对象,同时仅指定 a 和 d(被覆盖的值)。

0 个答案:

没有答案
相关问题