9

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
Nelson Tatius
  • 7,693
  • 8
  • 47
  • 70
  • Unless someone knows an update to the standard I'm not aware of, `typeid` is implementation defined, and as such so are the values it returns. If this is no longer the case I'm very curious to know more about it as well. Until then, the mangling algorithm specific to your compiler will likely lead you to the answer (and demangling) you're looking for. – WhozCraig Oct 13 '12 at 22:18
  • It's wholly implementation dependent. Microsoft's cl will use names similar to what you're expecting though. – obataku Oct 13 '12 at 22:21
  • related http://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c – Ciro Santilli OurBigBook.com Dec 17 '16 at 21:26

1 Answers1

20

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.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166