Why no overload chosen on forward reference for function templates?

58 views Asked by At

Snippet:

#include <iostream>

template<typename T>
struct Printer{};

template<typename T>
void test(T&&)
{
    std::cout << "Primary template called\n";
}

template<typename T>
void test(Printer<T>&&)
{
    std::cout << "Specialized template called\n";
}

int main()
{
    auto t = Printer<int>{};
    test(0);
    test(t);
}

Here is the demo

Why is two times Primary template called printed?

If one removes the forward reference from the second template, then the Printer overload is chosen.

Why is it not chosen with &&?

1

There are 1 answers

0
Jarod42 On BEST ANSWER

Forwarding reference only works for T&&, not C<T>&& nor const T&&.

test(0); // Call test(T&&) with T=int
test(t); // Call test(T&&) with T=Printer<int>&