Type of an auto initialized list

僤鯓⒐⒋嵵緔 提交于 2020-01-04 06:27:09

问题


In the C++ code below, what is type of a? typeid returns St16initializer_listIPKcE

auto a = { "lol", "life" };

回答1:


When you have

auto a = { "lol", "life" };

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*>.

If on the other have you had something like

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>

The expection is that before C++17

auto x5{ 3 };

is a std::intializer_list<int> where in C++17 and most compilers that already adopted the rule it is deduced as a int.




回答2:


The answer to your question is std::intializer_list<char const*>

If you want to learn non-mangled name of a type, you can use the undefined template trick:

template<typename T>
void get_type_name(T&&);

then call it

auto a = { "",  ""};
get_type_name(a);

You should get a readable error message stating something along the lines of

undefined reference to `void get_type_name<std::initializer_list<char const*>&>(std::initializer_list<char const*>&)'


来源:https://stackoverflow.com/questions/40094160/type-of-an-auto-initialized-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!