Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I explicitly view the results of type inference by auto?

I am newly studying auto feature of C++11/14.

For educational purpose, I would like to explicitly display the result of type inference of my code. I tried typeid().name(), but I found two problems with this approach.

  1. Output is sometimes difficult to understand. (For example, "NSt3__16vectorIiNS_9allocatorIiEEEE")
  2. const/volatile modifiers do not seem to be displayed.

@πάνταῥεῖ I have tried using abi::__cxa_demangle() you pointed out. Problem 1 is solved, thank you, but typeid().name() does not seem to contain CV modifier information. I think there are some pitfalls using auto keyword, so I would like to see the exact result of the type inference, including CV modifier and reference type.

I am using clang 6.1.0 on mac os 10.10.3, but I would like to know portable way to do this, if possible.

like image 753
tuun Avatar asked Apr 28 '15 10:04

tuun


Video Answer


2 Answers

Try the approach proposed by Scott Meyers (Effective Modern C++):

Declare a template (but don't define it)

template<typename T>       // declaration only for TD;
class TD;                  // TD == "Type Displayer"

Then instantiate this template using your type

TD<decltype(x)> xType

The compiler will now complain about this incomplete type (and usually will display the full name of it)

error: aggregate 'TD< int > xType' has incomplete type and cannot be defined

See Item 4 of "Effective Modern C++" (generally I'd propose this book as a "must read")

like image 82
Daniel Avatar answered Nov 01 '22 01:11

Daniel


Type Index library was recently added to Boost. It tries to address some of the problems you metioned.

Example:

cout << boost::typeindex::type_id<int const volatile*>().pretty_name() << endl;
cout << boost::typeindex::type_id_with_cvr<int const&>().pretty_name() << endl;

Prints:

int const volatile*
int const&
like image 25
Johny Avatar answered Nov 01 '22 00:11

Johny