There is often a need to get a readable type name at runtime:
#include <iostream>
#include <typeinfo>
template <class T>
void do_something(const T& x) {
if (x == 0) {
std::cout << "Error: x == 0. T is " << typeid(T).name()
<< std::endl;
}
// ...
}
However, the example from earlier is not very portable. It does not work when RTTI is disabled, and it does not always produce a nice human-readable name. On some platforms, code from earlier will output just i or d.
Things get worse if we need a type name without stripping the const, volatile, and references:
void sample1() {
auto&& x = 42;
std::cout << "x is "
<< typeid(decltype(x)).name()
<< std::endl;
}
Unfortunately, the preceding code outputs int in the best case, which is not what we were expecting.