Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert static type to string in C++ with gcc

Tags:

c++

gcc

typeof

This is the same question as Is it possible to print a variable's type in standard C++? but I don't want RTTI. I'm writing code with expression templates (e.g. Eigen), which means the types of my variables can be really involved and that I don't know the actual types. However, the compiler knows the types and can tell me when something goes wrong:

error: ‘const struct Eigen::EigenBase<Eigen::Matrix<double, 1, 1, 0, 1, 1> >’ ...

Is there any way I can convert a variable name to a string with the (static) type name so that I could debug the program without breaking it? E.g.

int a;
M b;
cout << TYPEOF(a) << endl << TYPEOF(b) << endl;

would print

int
const struct Eigen::EigenBase<Eigen::Matrix<double, 1, 1, 0, 1, 1> >’
like image 918
Mankka Avatar asked Nov 28 '25 22:11

Mankka


1 Answers

typeid can be applied to a type (5.2.8p4):

std::cout << typeid(int).name() << '\n'
  << typeid(M).name() << '\n';

This doesn't involve any run-time overhead.

like image 76
ecatmur Avatar answered Dec 01 '25 12:12

ecatmur



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!