Alex Rivera | Logout

Removing namespace of type name in C++

Asked 2011-10-08T08:01:36.650
24

In C++, when we use typeid to get type name of an object or class, it will show a decorated(mangled) string. I use cxxabi to demangle it:

#include <cxxabi.h>
#include <typeinfo>

namespace MyNamespace {

class MyBaseClass
{
public:
    const std::string name()
    {
        int status;
        char *realname = abi::__cxa_demangle(typeid (*this).name(),0,0, &status);
        std::string n = realname;
        free(realname);
        return n;
    }
};

}

int main()
{
    MyNamespace::MyBaseClass h;
    std::cout << h.name() << std::endl;
}

The output in gcc is:

MyNamespace::MyBaseClass

I need to remove MyNamespace:: from above string. i can remove them by string manipulating .

But is there a standard way with cxxabi or other libraries to do this or a clear solution?(At least portable between gcc and Visual C++)

Edit
Report

1 Answer

3

I dont know if this would corresponds to your needs but i liked to mention about it.

There is something you can do to get the name of a class that you had write. And it may be considered as portable between gcc and Visual C++.

In GCC there is a magic variable named __FUNCTION__ as part of the gnu c language extensions, which treated as a variable, in C++. ( Treating it differs in C according to the GCC version. )

In Visual Studio there is a predefined macro which is in the same name and does the same job. Description is here.

You use __FUNCTION__ to get the name of the current function. So, to get the name of the class, may be you can use it in class constructor like this:

namespace MyNamespace
{
    class MyBaseClass
    {
    public:
        MyBaseClass(): myName(__FUNCTION__){}
        string name() { return myName; }
    private:
        string myName;
    };
}

So, you get "MyBaseClass" response if you call name() function of an instance of this class.

answered 2011-10-17T13:36:54.097

Your Answer