Monday, 25 September 2017

c++ - Are there any use cases for std::forward with a prvalue?

Answer


The most common usage of std::forward is to, well, perfect forward a forwarding (universal) reference, like



template

void f(T&& param)
{
g(std::forward(param)); // perfect forward to g
}


Here param is an lvalue, and std::forward ends up casting it to a rvalue or lvalue, depending on what the argument that bounded to it was.



Looking at the definition of std::forward from cppreference.com I see that there is also a rvalue overload




template< class T >
T&& forward( typename std::remove_reference::type&& t );


Can anyone give me any reason why the rvalue overload? I cannot see any use case. If you want to pass a rvalue to a function, you can just pass it as is, no need to apply std::forward on it.



This is different from std::move, where I see why one wants also a rvalue overload: you may deal with generic code in which you don't know what you're being passed and you want unconditional support for move semantics, see e.g. Why does std::move take a universal reference?.



EDIT To clarify the question, I'm asking why overload (2) from here is necessary, and a use case for it.

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...