指定初始值设定项中参数列表的花括号数

number of braces for parameter list in designated initializer

即使我使用 C++2a 指定的初始值设定项,我目前仍在努力处理参数列表中的大括号数量。

我有一些嵌套结构,例如:

#include <string>
#include <optional> 

struct Base
{
    std::string name;
};

struct KL: public Base
{
    int p1;
    int p2;
};

struct FFA: public Base
{
    int pp1;
    int pp2;
    int pp3;
};

struct Spur
{
    std::optional< KL >              kl;
    std::optional< FFA >             ffa ;
};

struct Config
{
    std::string s;
    int i1;
    int i2;
    Spur spur;

    Config(
        const std::string& _s,
        int _i1,
        int _i2,
        const Spur& _spur
        ): s{_s},i1{_i1},i2{_i2},spur{_spur}{}
};

class Signal
{
    public:
        Signal( const Config& ) {}
};

struct A { int i; };
struct B { std::string s; };
struct X { A a; B b; };

int main()
    Spur s1{   .kl= {{ "XYZ", 1,2 }}}; // works! gcc+clang but clang warns "suggest braces around initialization of subobject"
    Spur s2{   .kl=  { "XYZ", 1,2 }} ; // fails! could not convert '{"XYZ", 1, 2}' from '<brace-enclosed initializer list>' to 'std::optional<KL>'
    Spur s3{ { .kl=  { "XYZ", 1,2 }}}; // works gcc! clang fails: no matching constructor for initialization of 'std::optional<KL>' 


    Config c1{ "ABC", 1,2 , {{ .kl=std::nullopt }}}; // works gcc, clang fails no matching constructor for initialization of 'Config'
    Config c2{ "ABC", 1,2 , {  .kl=std::nullopt }} ; // works for gcc and clang

    Signal si1{ {"ABC", 1,2 , {{ .kl = std::nullopt     }} }}; // gcc ok, clang fails: no matching constructor for initialization of 'Signal'
    Signal si2{ {"CDE", 3,4 , {{ .kl = KL{ "XYZ", 1,2 } }} }}; // gcc ok, clang fails: no matching constructor for initialization of 'Signal'
    Signal si3{ {"CDE", 3,4 , {{ .kl =   { "XYZ", 1,2 } }} }}; // gcc ok, clang fails: no matching constructor for initialization of 'Signal'
    Signal si4{ {"CDE", 3,4 , {  .kl = KL{ "XYZ", 1,2 }  } }}; // clang & gcc ok
    Signal si5{ {"CDE", 3,4 , {  .kl =   { "XYZ", 1,2 }  } }}; // gcc& clang fail: no matching function for call to 'Signal::Signal(<brace-enclosed initializer list>)'

    X x{ .b={"Hallo"  }}; 
    X x2{ .a={1} };

我的问题是: 当我在初始化列表中的参数集周围需要另一组大括号时?

我已经阅读了Nested braces and designated Initializers

使用的编译器: clang version 6.0.1g++ (GCC) 8.2.1 标志:-std=c++20

有人可以解释必须满足哪条规则才能消除所有错误和警告吗? (clang 总是警告缺少大括号,但我找不到应该在哪里设置不破坏 gcc 编译的额外大括号)。最好能得到一个可以在 gcc 和 clang 上编译的例子。

您可能会使用:

Spur s1{ .kl = {{ {"XYZ"}, 1,2 }}};
Config c1{ "ABC", 1,2 , { .kl = std::nullopt }};
Signal si1{ {"ABC", 1,2 , { .kl = std::nullopt} }};

Demo

您需要 {} 大约 "XYZ" 来初始化基础 class。
(您甚至可以再添加一个 {} 以更明确地从 const char* 构建 std::string :-) )

.kl = { { {"XYZ"}, 1,2 } }
      | | |
      | | v
      | | Base
      | v
      | KL
      v
      optional