指定的初始化程序中的参数列表的括号数量

时间:2019-03-14 15:49:19

标签: c++ initialization c++20

即使使用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上编译的示例将很高兴。

1 个答案:

答案 0 :(得分:2)

您可以使用:

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

Demo

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

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