I'm currently working on some logging code that supposed to – among other things – print information about the calling function. This should be relatively easy, standard C++ has a type_info
class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. typeid(std::vector<int>).name()
returns St6vectorIiSaIiEE
.
Is there a way to produce something useful from this? Like std::vector<int>
for the above example. If it only works for non-template classes, that's fine too.
The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
Best Solution
Given the attention this question / answer receives, and the valuable feedback from GManNickG, I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features.
In file type.hpp
In file type.cpp (requires C++11)
Usage:
It prints:
Type of ptr_base:
Base*
Type of pointee:
Derived
Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2).
If you cannot use C++11 features, here is how it can be done in C++98, the file type.cpp is now:
(Update from Sep 8, 2013)
The accepted answer (as of Sep 7, 2013), when the call to
abi::__cxa_demangle()
is successful, returns a pointer to a local, stack allocated array... ouch!Also note that if you provide a buffer,
abi::__cxa_demangle()
assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): "Ifoutput_buffer
is not long enough, it is expanded usingrealloc
." Callingrealloc()
on a pointer to the stack... ouch! (See also Igor Skochinsky's kind comment.)You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name not longer than 15 (so
realloc()
is not called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash.To verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call
realloc()
with a pointer to the stack.(The old answer from Dec 27, 2010)
Important changes made to KeithB's code: the buffer has to be either allocated by malloc or specified as NULL. Do NOT allocate it on the stack.
It's wise to check that status as well.
I failed to find
HAVE_CXA_DEMANGLE
. I check__GNUG__
although that does not guarantee that the code will even compile. Anyone has a better idea?