Is it possible to get a string that will contain the namespace and class name at compile time?

I wonder how to define a macro that for a given class name displays its namespace and class name in the format, for example: "Namespace.SubNamespace.ClassName"?

So write something like this:

// MyClass.h #include <string> namespace NS { namespace SNS { class MyClass { static std::string str; }; } } //MyClass.cpp #include <MyClass.h> using namespace std; string NS::SNS::MyClass::str = SUPER_MACRO(/*params if needed yet none would be prefered*/); 

I want str to be "NS.SNS.MyClass". I would really like the macro to have, if possible, profile parameters (which means one or nothing).

As an alternative, I wonder if this can be done using templates with something like:

 string NS::SNS::MyClass::str = GetTypeNameFormater<NS::SNS::MyClass>(); 

How to do it (using boost, stl and having only C ++ 03 at hand)?

+8
c ++ boost class c ++ 03
source share
2 answers

There is no standard way to do this. The only standard macro provided to provide volume information is the C99 __func__ macro.

What you can do is get the symbol name via std::typeinfo , and then drop it into a specific API for compilation and then parse the namespace.

http://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html gives examples of how to do this. This should work with clang and OS X as well.

Alternatively, you can write a set of macros to determine the namespaces and the corresponding static string, and then hack your strings together.

None of the options will be especially good.

+3
source share

This is not a compilation based approach, but it can give you what you want.

You can try something like:

 nm ./a.out | grep "ZN" | c++filt 

Buried at the exit, I see:

 NS::SNS::MyClass::str 

You can also use demangle.h , although I'm not sure how you get the name of the claim (typeid doesn't give me much.)

You can also use Boost Reflect , Boost Typetraits , Reflex or clang. Perhaps you can do some reflection using the clang API.

+1
source share

All Articles