Template argument output for string literals

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 in the recent g ++ compiler. Apparently, T is output as an array (instead of a pointer). Is this behavior guaranteed by the standard? I was a bit surprised because the following code prints the size of the pointer, and I thought that auto behaves exactly the same as the output of the template argument?

 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 } 
+6
source share
1 answer

auto behaves exactly 1 as the output of the template argument. Just 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 } 

Wherein:

 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.

+8
source

All Articles