AhSeng Fan
AhSeng Fan

Reputation: 467

Template deduction ambiguous

I am confused by rvalue concept of c++ now. I wrote the code below to check my understanding of rvalue is correct. But it turns out it it's not. I was expecting the output would be "T&&" but instead "T" was printed. Why?

To make it print "T&&", which part of the code requires change?

Thank you.

template <typename T>
struct printer {
    printer(T t)
    { 
        cout << "T" << endl;
    }
};

template <typename T>
struct printer<T&&> {
    printer(T&& t)
    {
        cout << "T&&" << endl;
    }
};

template <typename T>
struct printer<T&> {
    printer(T& t)
    {
        cout << "T&" << endl;
    }
};

int main()
{
    printer a(make_unique<int>(5));

    return 0;
}

Upvotes: 1

Views: 111

Answers (1)

Jarod42
Jarod42

Reputation: 217255

"T" was printed. Why?

Automatic deduction guides only consider primary template, not the specialization, so only

template <typename T> printer(T) -> printer<T>;

is generated.

To make it print "T&&", which part of the code requires change?

You may add deduction guide:

template <typename T> printer(T&&) -> printer<T&&>;

Demo

Note: that deduction guide would also works for printer<T&>.
You won't have printer<T> anymore with that guide.

Upvotes: 3

Related Questions