Search code examples
c++templatesc++11universal-reference

Behavior of C++ template function


Let's say I have this function:

bool f(int&& one, int&& two) { }

If I attempt to call it with this code:

int x = 4;
f(x, 5);

the compiler will complain that it cannot convert x from lvalue reference to rvalue reference, which is correct.

Now if I convert f into a template function like this:

template <class T, class U>
bool f(T&& one, U&& two) { }

then I can call it with an lvalue reference:

int x = 5;
f(x, 5);

Why is it so? Why doesn't the compiler complain in this case?


Solution

  • Because there is a template argument deduction, reference collapsing happens. It is what Scott Meyers calls universal references. The U&& will actually become int &. There is a nice article and video about how it works and how it could be used.