How to combine base-class explicit constructor and designated initialization in g++-10?

Viewed 145

I have a trivial example:

struct A {
    explicit A(int a) : a(a) {}
 protected:
    int a;
};
struct B : public A { int b = 0, c = 0; };

// Attempts to get the code compiled:
B b1 { A(1),   .c = 2 };  // fine with clang-11
B b2 { A{1},   .c = 2 };
B b3 { .A{1},  .c = 2 };
B b4 { {1},    .c = 2 };
B b5 { .a = 1, .c = 2 };

The first example fails on g++10 -std=c++20 with error:

error: either all initializer clauses should be designated or none of them should be

While it's ok on clang++-11.

Is there any proper syntactic way to achieve the following:

  • initialize base object with explicit constructor,
  • partially initialize structure.

Or is the Clang compiler non-conformant with C++20 standard in this particular case? I saw this question and its answer suggests that it is so: mixing designated initializers with non-designated initializers, which is not allowed.

1 Answers

You cannot. At present, there is no way to use designated initializers in a braced-init-list that also needs to initialize a base class. There's a proposal for it, but it's obviously not in C++ at present.

Related