c++c++11typeinfo

Why is the output of `typeid(T&).name()` given as `T` instead of `T&`?


As the subject, you could check the related code on https://godbolt.org/z/qtjVP6.

For your convience, the code is posted below:

#include<typeinfo>
#include<iostream>

class Widget{};

Widget someWidget;

int main()
{
    Widget&& var1 = Widget{};      // here, “&&” means rvalue reference
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference

    std::cout << typeid(var2).name() << std::endl;
}

Output:6Widget

echo 6Widget | c++filt -t says Widget.

I would be grateful to have some help on this question.


Solution

  • Per C++ Reference (emphasis mine):

    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.

    So for type = T&, typeid(type) will give results about T (reference removed).

    It's easy to understand IMO, as for all purposes, a variable of type T& is functionally equivalent to one of type T.