Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

human-readable type_info.name() [duplicate]

Tags:

c++

typeid

I've compiled the following code with g++, and got output, which written in comments.

template<class T>
void foo(T t) { cout << typeid(t).name() << endl; }

int main() {
    foo("f");       //emits "PKc"
    foo(string());  //emits "Ss"
}

I know, that type_info.name() isn't standartized, but is there any way to get human-readable results?

Something like the following would be good enought

const char *
class string
like image 911
Nelson Tatius Avatar asked Oct 13 '12 22:10

Nelson Tatius


1 Answers

You can use abi::__cxa_demangle for that (demangle function taken from here), just remember that the caller is responsible for freeing the return:

#include <cxxabi.h>
#include <typeinfo>
#include <iostream>
#include <string>
#include <memory>
#include <cstdlib>

std::string demangle(const char* mangled)
{
      int status;
      std::unique_ptr<char[], void (*)(void*)> result(
        abi::__cxa_demangle(mangled, 0, 0, &status), std::free);
      return result.get() ? std::string(result.get()) : "error occurred";
}

template<class T>
void foo(T t) { std::cout << demangle(typeid(t).name()) << std::endl; }

int main() {
    foo("f");            //char const*
    foo(std::string());  //std::string
}

Example on ideone.

like image 73
Jesse Good Avatar answered Oct 01 '22 10:10

Jesse Good