Readable form of typeid?

Fred Finkle picture Fred Finkle · Jul 29, 2012 · Viewed 7.7k times · Source

Is there a compiler out there that returns the name of a type in a readable fashion (or library providing that functionality or tool). Essentially what I want is the string corresponding to the type expression you'd write it in your source code.

Answer

steffen picture steffen · Jul 29, 2012
 typeid(var).name()

is what you are looking for. The output differs from compiler to compiler though... For gcc the output for int is i, for unsigned is j, for example. Here is a small test program:

#include <iostream>
#include <typeinfo>

struct A { virtual ~A() { } };
struct B : A { };

class C { };
class D : public C { };

int main() {
  B b;
  A* ap = &b;
  A& ar = b;
  std::cout << "ap: " << typeid(*ap).name() << std::endl;
  std::cout << "ar: " << typeid(ar).name() << std::endl;

  D d;
  C* cp = &d;
  C& cr = d;
  std::cout << "cp: " << typeid(*cp).name() << std::endl;
  std::cout << "cr: " << typeid(cr).name() << std::endl;

  int e;
  unsigned f;
  char g;
  float h;
  double i;
  std::cout << "int:\t" << typeid(e).name() << std::endl;
  std::cout << "unsigned:\t" << typeid(f).name() << std::endl;
  std::cout << "char:\t" << typeid(g).name() << std::endl;
  std::cout << "float:\t" << typeid(h).name() << std::endl;
  std::cout << "double:\t" << typeid(i).name() << std::endl;
}

See also this question: typeid(T).name() alternative in c++11?