Getting type names at compile time in C ++

I want to get the type name and print it for debugging purposes. I am using the following code:

#include <cxxabi.h> inline const char* demangle(const char *s) { abi::__cxa_demangle(s, 0, 0, NULL); } template<typename T> inline const char* type_name() { return demangle(typeid(T).name()); } 

This works well, but I think the overhead is superfluous. Is there a way to get a human-readable form of type identifiers that is computed at compile time? I am thinking of something that looks like this:

 boost::mpl::type_name<MyType>::value 

Which will return the string constant of the type name.

As a question (not so strict): is it possible to perform line processing with boost :: mpl?

+4
source share
4 answers

I do not see typeid(T).name() execute overhead at runtime. typeid(expr) yes, if expr has a polymorphic type.

It seems that demangling probably occurs at runtime, but there is nothing terrible about it. If this is only for debugging, then I really would not worry too much about it if your profiler does not indicate that it causes your program to slow down so much that debugging its other elements is difficult.

+5
source

I have the same need, I decided to use it with the __ FUNCTION __ macro in the static method of my class. But you have to do some runtine calculation on __ FUNCTION __ to extract the class name. You have to do some template tricks to avoid inserting the same code in each class. If someone asked, I can clear and translate my code from French to publish it.

The main advantage of this method is that you do not need to enable RRTI . Retrieving a class name, on the other hand, may be compiler dependent.

+2
source

You can use std :: type_index to cache changed name strings.

+1
source

You can use std :: map or a similar data structure (for example, splay trees) for caching and quick access to the demarched name. This was not done at compile time, but I doubt the latter is possible.

+1
source

All Articles