I would like to print the name of a type for debugging purposes, so I've created a function which does the trick (in fact, I borrowed it from another SO answer, which I cannot found now), the function looks like this:
template <typename T> std::string TypeName(T)
{
auto name = typeid(T).name();
int status = 0;
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return ((status == 0) ? res.get() : name);
}
It works fine:
int i = 0;
float f = 0.f;
std::cout << TypeName(i) << '\n'; // int
std::cout << TypeName(f) << '\n'; // float, so far so good
std::cout << TypeName(&i) << '\n'; // int *
std::cout << TypeName(&f) << '\n'; // float *, as expected
But it lacks of the capacity of dealing with top-level cv-cualifiers and references:
const int ci = 1;
const float cf = 1.f;
std::cout << TypeName(ci) << '\n'; // int! (instead of const int)
std::cout << TypeName(cf) << '\n'; // float! (instead of const float)
int &ri = i;
float &rf = f;
std::cout << TypeName(ri) << '\n'; // int! (instead of int &)
std::cout << TypeName(rf) << '\n'; // float! (instead of float &)
Well, I can't say that this is unexpected, because the function TypeName
is a function template and the type T
follows the template type deduction but this issue makes the whole thing almost useless.
So, my question is: Is there anything that can be done in order create a template function (which can get any type as input) to obtain the type name without loosing the top-level cv-cualifiers and references?
Thanks in advance.