According to the C++23 standard, what is the output of this program?
#include <iostream>
#include <type_traits>
int main() {
auto a = "Hello, World!";
std::cout << std::is_same_v<decltype("Hello, World!"), decltype(a)>;
return 0;
}A string literal is an lvalue, and its type is "array of n const char".
The type of a is deduced using the rules for template argument deduction.
0
decltype is used twice, once with "Hello World" and once with a. §[dcl.type.decltype]¶1 has the details:
For decltype("Hello World"), we have:
— otherwise, if
Eis an lvalue,decltype(E)isT&, whereTis the type ofE;
A string literal is an lvalue, and its type is "array of n const char" (§[lex.string]¶1), so decltype("Hello, World!") is const char(&)[14].
For decltype(a), we have:
— otherwise, if
Eis an unparenthesized id-expression (...),decltype(E)is the type of the entity named byE.
So decltype(a) is the type of a. The type of a is however not const char(&)[14], but rather const char*, due to the following:
If the placeholder-type-specifier is of the form type-constraintopt
auto, the deduced typeT'replacingTis determined using the rules for template argument deduction. (...) ObtainPfromTby replacing the occurrences of type-constraintoptautoeither with a new invented type template parameterU(...). Deduce a value forUusing the rules of template argument deduction from a function call, wherePis a function template parameter type and the corresponding argument isE. (...)T'is obtained by substituting the deducedUintoP.
In other words, the type of a will be deduced the same way as if we passed "Hello, World!" as a template argument of a function.
If
Pis not a reference type:— If
Ais an array type, the pointer type produced by the array-to-pointer standard conversion is used in place ofAfor type deduction;
where P is a template parameter and A is the type of the argument.
This means that the type of a is the result of array-to-pointer conversion of the type of "Hello, World!" (const char(&)[14]) which is const char*.