简体   繁体   English

带 auto 的 initializer_list 包含多个表达式

[英]initializer_list with auto contains multiple expressions

Rather simple question,比较简单的问题,

auto x11 {1,2,3,4};
auto x1 = {1,2,3,4};
auto x22 {1.0, 2.25, 3.5};
auto x2 = {1.0, 2.25, 3.5};

As far as I understand, there should be no difference here with respect to having = or not.据我了解,这里是否有=应该没有区别。 However, using llvm/clang 6.0.0 (with --std=c++17), I get :但是,使用 llvm/clang 6.0.0(使用 --std=c++17),我得到:

main1.cpp:35:17: error: initializer for variable 'x11' with type 'auto' contains multiple
  expressions
auto x11 {1,2,3,4};
~~~~~~~~    ^

main1.cpp:37:20: error: initializer for variable 'x22' with type 'auto' contains multiple
  expressions
auto x22 {1.0, 2.25, 3.5};

From Stroustroup's C++ book, page.162:来自 Stroustroup 的 C++ 书,第 162 页:

auto x1 {1,2,3,4}; // x1 is an initializer_list<int>
auto x2 {1.0, 2.25, 3.5 }; // x2 is an initializer_list of<double>

So, is there really a problem in not having = in there?那么,那里没有=真的有问题吗?

The rule of auto type deduction changed since N3922 .N3922以来, 自动类型推导的规则发生了变化。 (This is considered as a defect in C++14). (这被视为 C++14 中的缺陷)。

In direct-list-initialization (but not in copy-list-initalization), when deducing the meaning of the auto from a braced-init-list, the braced-init-list must contain only one element, and the type of auto will be the type of that element:在直接列表初始化中(但不是在复制列表初始化中),当从花括号初始化列表中推导出 auto 的含义时,花括号初始化列表必须只包含一个元素,并且 auto 的类型将是该元素的类型:

 auto x1 = {3}; // x1 is std::initializer_list<int> auto x2{1, 2}; // error: not a single element auto x3{3}; // x3 is int // (before N3922 x2 and x3 were both std::initializer_list<int>)

So before N3922, all the variables in your sample work fine and have type std::initializer_list<int> .因此,在 N3922 之前,示例中的所有变量都可以正常工作,并且类型为std::initializer_list<int> But since N3922, for direct initialization (ie for x11 and x22 ) the braced-initializer must contain only one element (and their type would be the type of the element), then the code become ill-formed.但是由于 N3922,对于直接初始化(即对于x11x22 ),花括号初始化器必须只包含一个元素(并且它们的类型将是元素的类型),然后代码变得格式错误。

See N3922 and N3681 for more.有关更多信息,请参阅N3922N3681

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM