Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 292
DuckQueen Avatar asked Dec 02 '13 10:12

DuckQueen


1 Answers

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.

like image 134
pmr Avatar answered Sep 25 '22 02:09

pmr