The code below prints l-value
:
#include <iostream>
namespace
{
void foo(const int&)
{
std::cout << "const l-value" << std::endl;
}
void foo(int&)
{
std::cout << "l-value" << std::endl;
}
void foo(int&&)
{
std::cout << "r-value" << std::endl;
}
}
int main()
{
int&& x = 1;
foo(x);
return 0;
}
The type of variable x
is int&&
, but the value category of expression x
is l-value
.
That is why we need std::forward
:
template <typename T>
void deduce(T&& x)
{
//at this point expression x is l-value,
//because it is a named variable.
foo(std::forward<T>(x));
}
int main()
{
//we pass r-value
deduce(1);
return 0;
}