自动初始化列表的类型 [英] Type of an auto initialized list
问题描述
在下面的C ++代码中,a
的类型是什么? typeid
返回St16initializer_listIPKcE
In the C++ code below, what is type of a
? typeid
returns St16initializer_listIPKcE
auto a = { "lol", "life" };
推荐答案
有空时
auto a = { "lol", "life" };
编译器将尝试推导std::initializer_list
,其中类型是所有元素的含义.在这种情况下,"lol"
和"life"
都是const char[]
,所以您有一个std::initializer_list<const char*>
.
The compiler will try to deduce a std::initializer_list
where the type is what all of the elements are. In this case "lol"
and "life"
are both a const char[]
so you have a std::initializer_list<const char*>
.
如果您有类似的东西
auto foo = { 1, 2.0 };
然后,由于元素类型不同,您将遇到编译器错误.
Then you would have a compiler error since the element types are different.
带有一个期望的自动推论器列表的规则如下
The rules for auto deduction of intializer list are as follows with one expection
auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
auto x2 = { 1, 2.0 }; // error: cannot deduce element type
auto x3{ 1, 2 }; // error: not a single element
auto x4 = { 3 }; // decltype(x4) is std::initializer_list<int>
期望是在C ++ 17之前
The expection is that before C++17
auto x5{ 3 };
是std::intializer_list<int>
,在C ++ 17中,大多数已经采用该规则的编译器都将其推导为int
.
is a std::intializer_list<int>
where in C++17 and most compilers that already adopted the rule it is deduced as a int
.
这篇关于自动初始化列表的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!