DuckQueen
DuckQueen

Reputation: 800

Is it possible to get a string that would containing namespace and class name at compile time?

I wonder how to define a macro that would for given class name output its namespace and class name in a format like: "Namespace.SubNamespace.ClassName"?

So writting 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 to get str to be "NS.SNS.MyClass". I would love that macro have as fiew params if possible (meaning one or none).

Alternatively I wonder if such thing can be done using templates with something like:

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

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

Upvotes: 8

Views: 2865

Answers (2)

user1508519
user1508519

Reputation:

This is not a compile-time approach, but it may give you what you want.

You can try something like:

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

Buried in the output I see:

NS::SNS::MyClass::str

You can also use demangle.h, although I'm not sure how you'd obtain the mangled name (typeid does not give me much.)

You can also consider using Boost Reflect, Boost Typetraits, Reflex or clang. You might be able to do some sort of reflection using clang's API.

Upvotes: 1

pmr
pmr

Reputation: 59811

There is no standard way to do this. The only standard macro provided to give information about the scope is the C99 macro __func__.

What you can do though is to get the name of the symbol through std::typeinfo and then throw it into a compiler specific demangling API and then parse out the namespace.

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

Alternatively you can write a set of macros to define namespaces and a corresponding static string and then hack your strings together from there.

Neither option is going to be particularly pretty.

Upvotes: 3

Related Questions