Vik*_*nko 23 c++ language-lawyer auto c++17
相当简单的问题,
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};
Run Code Online (Sandbox Code Playgroud)
据我了解,这里应该没有区别=
.但是,使用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};
Run Code Online (Sandbox Code Playgroud)
从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>
Run Code Online (Sandbox Code Playgroud)
那么,在那里没有=真的有问题吗?
son*_*yao 22
自C++ 17以来,自动类型推导的规则发生了变化.
(自C++ 17开始)
在直接列表初始化中(但不在copy-list-initalization中),当从braced-init-list推导出auto的含义时,braced-init-list必须只包含一个元素,auto的类型将是该元素的类型:Run Code Online (Sandbox Code Playgroud)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开始,对于直接初始化(即for x11
和x22
),braced-initializer必须只包含一个元素(并且它们的类型将是元素的类型),然后变成格式错误的代码.
归档时间: |
|
查看次数: |
893 次 |
最近记录: |