0

I've got this exercise:

auto        p = 42;
auto const& q = p;
auto        r = q;
auto&       s = q;

What is the type of r and s?

This is my answer but I'm not very sure:

auto        p = 42;        // int
auto const& q = p;         // const int&
auto        r = q;         // int&
auto&       s = q;         // int&&

1 Answers1

2

I found a way to determine those variables types and their qualifier (const or &):

from this post Is it possible to print a variable's type in standard C++?

from the answer of Howard Hinnant:

The C++11 Solution

I am using __cxa_demangle for non-MSVC platforms as recommend by ipapadop in his answer to demangle types. But on MSVC I'm trusting typeid to demangle names (untested). And this core is wrapped around some simple testing that detects, restores and reports cv-qualifiers and references to the input type.

#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;
}

(endquote)

So, in main function:

int main()
{
    auto p = 42;
    auto const& q=p;
    auto r = q;
    auto& s=q;
    cout << "decltype(p) is " << type_name<decltype(p)>() << '\n';
    cout << "decltype(q) is " << type_name<decltype(q)>() << '\n';
    cout << "decltype(r) is " << type_name<decltype(r)>() << '\n';
    cout << "decltype(s) is " << type_name<decltype(s)>() << '\n';
}

the output is:

decltype(p) is int
decltype(q) is int const&
decltype(r) is int
decltype(s) is int const&