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++)
There is no standard way to do this, period, because there is no standard way to do name mangling. How to represent names was intentionally unspecified. There is no ABI in the C++ standard. The function you are using,
abi::__cxa_demangle, is a part of the Itanium C++ ABI. That function may or may not exist elsewhere.As far as a way to do what you want using the Itanium C++ ABI, they intentionally do not provide such a capability.