mr.engineer
mr.engineer

Reputation: 197

Right reference on lvalue

When does rvalue become right reference on lvalue?

Example is the following, and it should be solved with std::forward:

void g(int && v1, int & v2)
{
    std::cout << v1 << " " << ++v2 << std::endl;
}

template <typename F, typename T1, typename T2>
void flip(F f,T1 && t1, T2  && t2){
    g(t2, t1);
}

Error occurs on call like this:

flip(g, j, 2);

My problem is: in flip(g, j 2), third argument 2 is rvalue.
In function flip, argument t2 is right reference on 2. When g is called, it seems that t2 is right reference to lvalue.
In what point did rvalue, received by reference (without copying?), became lvalue?

Here is example: https://ideone.com/cJvFCg

Upvotes: 2

Views: 129

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

There's the "if it has a name" rule saying that within code like this, if the variable has a name (in this case, your t2) then at that point it becomes an lvalue. (See also Scott Meyers Effective Modern C++.)

To preserve the original intent of the caller, you would indeed use perfect forwarding:

g(std::forward<T2>(t2), ...)

Upvotes: 5

Related Questions