Confusion with universal links
I have this code:
void f2(int& lvalue)
{
std::cout <<"lvalue\n";
}
void f2(int&& rvalue)
{
std::cout << "rvalue\n";
}
template<typename T>
void f(T&& param)
{
f2(param);
}
I expect to get an "lvalue" if I call f:
int v = 10;
f(v);
and expect "rvalue" if I call f with:
f(10);
However, I always get an lvalue case. Please someone can explain where I am going wrong.
+3
source to share
1 answer
You need to redirect your parameter. Although the type param
can be an rvalue reference, it is param
itself still an lvalue.
f2(std::forward<T>(param));
std::forward
ensures that it param
receives the same reference qualifier as the passed argument. This is called a perfect forwarding .
If you call f(10)
:
-
param
- the lvalue -
std::move(param)
is an rvalue -
std::forward<T>(param)
in rvalue
If you call f(v)
:
-
param
- the lvalue -
std::move(param)
is an rvalue -
std::forward<T>(param)
in lvalue
+9
source to share