Blood-HaZaRd
Blood-HaZaRd

Reputation: 2124

auto and delctype(auto) type deduction example

I read an article about auto type deduction with decltype and I am wondering if my logic is correct about how type is deduced in the example below (so if I am mistaken please correct me :)

#include <iostream>
using namespace std;

class Widget
{
public:
    Widget() = default;
};

int main()
{
    Widget w;
    const Widget& cw = w;          // cw is const Widget&
    auto myWidget1 = cw;           // (1) myWidget1  is Widget
    decltype(auto) myWidget2 = cw; // (2) myWidget2 is const Widget&
}

So far what I understood is that :

for 1 : the auto type deduction is used and in this case it is like temlpate type deduction for parms passed by value. Which means the cv-qualifiers and refs are ignored which will result in Widget as type in the end.

for 2: the decltype is used and then passed to auto what really is cw a const Widget& and then all are set and the type is const Widget&.

So is what I wrote/understood right or wrong ?

Thank you

Upvotes: 3

Views: 200

Answers (1)

geza
geza

Reputation: 29962

Here's a trick, so you can make the compiler to print a type:

template <typename>
struct TD;

Then use:

TD<decltype(myWidget1)>();

As TD<...> is an incomplete type, the compiler will complain, and will print your type in the error message:

error: invalid use of incomplete type struct TD<Widget>

So myWidget1's type is Widget.

Type of myWidget2:

error: invalid use of incomplete type struct TD<const Widget&>

So its type is indeed const Widget &, as you suspected.

So yes, what you've described is right.

Upvotes: 7

Related Questions