function template
<utility>
std::forward
| lvalue (1) | template <class T> T&& forward (typename remove_reference<T>::type& arg) noexcept; |
|---|---|
| rvalue (2) | template <class T> T&& forward (typename remove_reference<T>::type&& arg) noexcept; |
Forward argument
If arg is an lvalue reference, the function returns arg without modifying its type.
This is a helper function to allow perfect forwarding of arguments taken as rvalue references to deduced types, preserving any potential move semantics involved.
The need for this function stems from the fact that all named values (such as function parameters) always evaluate as lvalues (even those declared as rvalue references), and this poses difficulties in preserving potential move semantics on template functions that forward arguments to other functions.
Both signatures return the same as:
|
|
By providing two signatures and using remove_reference on T, any instantiation is forced to explicitly specify the type of T (any implicitly deduced T would have no match).
Parameters
- arg
- An object.
Return value
If arg is an lvalue reference, the function returns arg with its type unchanged.Otherwise, the function returns an rvalue reference (
T&&) that refers to arg that can be used to pass an rvalue.Example
|
|
Output:
calling fn with lvalue: [lvalue][lvalue] calling fn with rvalue: [lvalue][rvalue]
Data races
noneExceptions
No-throw guarantee: this function never throws exceptions.See also
- move
- Move as rvalue (function template)