Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact type of "" when deduced by `auto`?

In this line:

auto a = "Hello World";

What is the exact Type of a? I'd guess char[] or const char* const but I'm not sure.

like image 448
TNA Avatar asked Dec 10 '22 21:12

TNA


1 Answers

N4296 2.13.5/8

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration (3.7).

But since variable is initialized as in your code it is actually const char*, you can check it like this.

template<typename> struct TD;

int main()
{
   auto a = "Hello World";
   TD<decltype(a)> _;
}

Here will be compile error in which you can see the actual type of TD instance, something like this with clang

error: implicit instantiation of undefined template 'TD<const char *>'

N4296 7.1.6.4

If the placeholder is the auto type-specifier, the deduced type is determined using the rules for template argument deduction.

template<typename> struct TD;

template<typename T>
void f(T) 
{
   TD<T> _;
}

int main()
{
   auto c = "Hello";
   TD<decltype(c)> _;
   f("Hello");
}

Both instantiated objects of type TD has type TD<const char*>.

N4926 14.8.2.1

Template argument deduction is done by comparing each function template parameter type (call it P) with the type of the corresponding argument of the call (call it A) as described below.

If P is not a reference type:

If A is an array type, the pointer type produced by the array-to-pointer standard conversion (4.2) is used in place of A for type deduction

like image 149
ForEveR Avatar answered Dec 13 '22 11:12

ForEveR