4
#include <iostream>

using namespace std;

int main()
{
    cout << typeid(int).name() << endl;
    cout << typeid(int&).name() << endl;
    cout << typeid(int&&).name() << endl;
    cout << typeid(const int).name() << endl;
    cout << typeid(const int&).name() << endl;
    cout << typeid(const int&&).name() << endl;
}

I think the output should be:

int
int&
int&&
const int
const int&
const int&&

However, the real output is:

int
int
int
int
int
int

Both of clang & vc++ do the same way.

Is there a reliable way to check the exact type name (with cv-ref-pointer traits) in C++?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • Not in a portable way. – Cornstalks Jul 31 '19 at 04:03
  • Any implemetation-defined way is also acceptable. – xmllmx Jul 31 '19 at 04:04
  • 1
    possible duplicate of [https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c](https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c) – shinxg Jul 31 '19 at 04:08
  • Possible duplicate of [Is it possible to print a variable's type in standard C++?](https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c) – L. F. Jul 31 '19 at 04:09

1 Answers1

2

Note that when you pass a reference type to typeid operator, the result std::type_info object represents the referenced type. And cv-qualifiers will be ignored.

1) Refers to a std::type_info object representing the type type. If type is a reference type, the result refers to a std::type_info object representing the referenced type

In all cases, cv-qualifiers are ignored by typeid (that is, typeid(const T) == typeid(T))

And note that what std::type_info::name returns is implementation-defined.

You can apply the trick from Effective Modern C++ (Scott Meyers) Item 4: Know how to view deduced types, to get the type name at compile-time. e.g.

template <typename>
struct TD;

then use it as

TD<int> td;

you'll get some message mentioning the type name, like

error: implicit instantiation of undefined template 'TD<int>'

LIVE (clang)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405