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

左心房为你撑大大i 提交于 2019-12-08 16:31:47

问题


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)?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/20325960/is-it-possible-to-get-a-string-that-would-containing-namespace-and-class-name-at

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!