I was wondering if it is possible in C++ to retrieve the name of a class in string form without having to hardcode it into a variable or a getter. I\'m aware that none of th
You can use typeid:
#include
std::cout << typeid(obj).name() << "\n";
However, the type name isn't standardided and may differ between different compilers (or even different versions of the same compiler), and it is generally not human readable because it is mangled.
On GCC and clang (with libstdc++ and libc++), you can demangle names using the __cxa_demangle function (on MSVC demangling does not seem necessary):
#include
#include
#include
#include
std::string demangle(char const* mangled) {
auto ptr = std::unique_ptr{
abi::__cxa_demangle(mangled, nullptr, nullptr, nullptr),
std::free
};
return {ptr.get()};
}
This will still not necessarily be a readable name — for instance, std::string is a type name for the actual type, and its complete type name in the current libstdc++ is std::__cxx11::basic_string; by contrast, in the current libc++ it’s std::__1::basic_string. “Prettifying” type aliases is unfortunately not trivial.