【发布时间】:2019-08-05 14:24:43
【问题描述】:
即使我使用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.1 和 g++ (GCC) 8.2.1 标志:-std=c++20
有人可以解释必须满足哪个规则才能消除所有错误和警告吗? (clang 总是警告缺少大括号,但我不知道应该在哪里设置其他不破坏 gcc 编译的大括号)。最好能得到一个可以在 gcc 和 clang 上编译的示例。
【问题讨论】:
标签: c++ initialization c++20