Is there a typeid for references?

c++, c++11, type-conversion, types

Solution

See this answer for the C++11 way to do it - it involves using type_traits. Here is the relevant section of code:

#include <type_traits>
#include <typeinfo>
#ifndef _MSC_VER
#   include <cxxabi.h>
#endif
#include <memory>
#include <string>
#include <cstdlib>

template <class T>
std::string
type_name()
{
    typedef typename std::remove_reference<T>::type TR;
    std::unique_ptr<char, void(*)(void*)> own
           (
#ifndef _MSC_VER
                abi::__cxa_demangle(typeid(TR).name(), nullptr,
                                           nullptr, nullptr),
#else
                nullptr,
#endif
                std::free
           );
    std::string r = own != nullptr ? own.get() : typeid(TR).name();
    if (std::is_const<TR>::value)
        r += " const";
    if (std::is_volatile<TR>::value)
        r += " volatile";
    if (std::is_lvalue_reference<T>::value)
        r += "&";
    else if (std::is_rvalue_reference<T>::value)
        r += "&&";
    return r;
}

Problem

I am looking for a way to obtain the name of a type, similar to `typeid` but for references. According to this page, `typeid` removes the reference. If type is a reference type, the result refers to the referenced type. I am looking for code similar to ``` int x = 5; int & y = x; wcout << typeid( y ).name(); ``` but whose output is "int &" rather than "int".

Original source

Related problems