Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readable form of typeid?

Tags:

c++

c++11

typeid

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.

like image 364
Fred Finkle Avatar asked Oct 28 '25 20:10

Fred Finkle


2 Answers

 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?

like image 60
steffen Avatar answered Oct 30 '25 12:10

steffen


while making search for this question, I have just found what I need in the boost library: boost::core::demangle

IN my case it was for catching exceptions:

try {
  //...
} catch (std::exception& e) {
  boost::core::scoped_demangled_name demangled(typeid(e).name());
  std::cerr << "ERROR: " << demangled.get() << ": " << e.what() << std::endl;
}
like image 40
QuentinC Avatar answered Oct 30 '25 10:10

QuentinC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!