template<typename T>
void print_size(const T& x)
{
std::cout << sizeof(x) << '\n';
}
int main()
{
print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
// prints 115
}
This prints 115 on a recent g++ compiler. So apparently, T
is deduced to be an array (instead of a pointer). Is that behavior guaranteed by the standard? I was a little bit surprised, because the following code prints the size of a pointer, and I thought auto
behaves exactly like template argument deduction?
int main()
{
auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
print_size(x);
// prints 4
}
Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation (to create strings by doing substitution of placeholders).
Template argument deduction is used in declarations of functions, when deducing the meaning of the auto specifier in the function's return type, from the return statement.
Strings in C are arrays of char elements, so we can't really return a string - we must return a pointer to the first element of the string. All forms are perfectly valid. Note the use of const , because from the function I'm returning a string literal, a string defined in double quotes, which is a constant.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.
auto
behaves exactly1 like template argument deduction. Exactly like T
!
Compare this:
template<typename T>
void print_size(T x)
{
std::cout << sizeof(x) << '\n';
}
int main()
{
print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
// prints 4
auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
print_size(x);
// prints 4
}
With this:
template<typename T>
void print_size(const T& x)
{
std::cout << sizeof(x) << '\n';
}
int main()
{
print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
// prints 115
const auto& x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
print_size(x);
// prints 115
}
1 Not quite, but this is not one of the corner cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With