具有auto的initializer_list包含多个表达式 [英] initializer_list with auto contains multiple expressions
问题描述
一个简单的问题,
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};
据我了解,此处是否具有=
应该没有区别.但是,使用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};
摘自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>
那么,那里没有 = 真的有问题吗?
自动的规则类型推论自C ++ 17以来已更改.
(自C ++ 17起)
在直接列表初始化中(但不在复制列表初始化中), 当从大括号初始化列表中推导auto的含义时, braced-init-list必须仅包含一个元素,并且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 C++17 x2 and x3 were both std::initializer_list<int>)
因此,在C ++ 17之前,示例中的所有变量都可以正常工作,并且类型为std::initializer_list<int>
.但是从C ++ 17开始,对于直接初始化(即x11
和x22
),支撑初始化器必须只包含一个元素(它们的类型将是元素的类型),然后成为格式错误的代码. /p>
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 :
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:
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 C++17.
(since C++17)
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 x1 = {3}; // x1 is std::initializer_list<int> auto x2{1, 2}; // error: not a single element auto x3{3}; // x3 is int // (before C++17 x2 and x3 were both std::initializer_list<int>)
So before C++17, all the variables in your sample work fine and have type std::initializer_list<int>
. But since C++17, for direct initialization (i.e. for x11
and x22
) the braced-initializer must contain only one element (and their type would be the type of the element) then become ill-formed code.
这篇关于具有auto的initializer_list包含多个表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!