Question:
I want to print the complete type of a variable to the console. The problem is that typeid (). Name () only infers the base type, discarding the const modifiers and the reference part. Is it possible to somehow correct this and display it in full, for example:
int x = 10;
const int& rx = x;
std::cout << typeid(rx).name() << std::endl; // Хочется, чтобы вывело const int&, а не int
Answer:
Directly not. You can make an empty template a la template <typename T> struct A {};
, and print the name A<decltype(rx)>
.
Note that typeid(...).name()
returns a nice human-readable name only in MSVC. In GCC and Clang, you get a mangled name.
Therefore, a more reliable way is like this:
template <typename T>
const char *TypeName()
{
#ifdef _MSC_VER
return __FUNCSIG__;
#else
return __PRETTY_FUNCTION__;
#endif
}
In my Clang, TypeName<decltype(rx)>()
returns const char *TypeName() [T = const int &]
.
Homework is to learn how to take out the type name from the returned string, automatically determining how many characters to discard at the beginning and at the end.
On the 5th plus – to do it at compile time, so that the extra parts of the line do not end up in the compiled program.