问题
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