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.
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.
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
Unless you've reason to think it'd be implementation or un-defined, can just test:
#include <iostream>
template <typename T> void f() { std::cout << "other\n"; }
template <> void f<const char*>() { std::cout << "const char*\n"; }
template <> void f<const char* const>()
{ std::cout << "const char* const\n"; }
template <> void f<const char(&)[12]>() { std::cout << "const char[12]\n"; }
int main()
{
auto a = "Hello World";
f<decltype(a)>();
}
Output:
const char*
Checking that ++a
compiles is another clue (it does), and while implementation defined #include <typeinfo>
/ typeid(a).name()
can often help answer such questions.
Change to auto& a
and you'll see a
changes to const char(&)[12]
.
You can print the type of a using typeinfo
int main()
{
auto a = "Hello World";
std::cout << "type is: " << typeid(a).name() << '\n';
}
on gcc it will print
pi is: PKc
which stands for pointer to constant char If you're in Windows the output will be a lot more readable, but you get used to this syntax too.
If you know more or less which type you a re looking for, you can also check if two types are equivalent with:
#include <typeinfo>
std::cout << std::is_same<const char*, decltype(a)>::value << std::endl;