std::forward (3) - Linux Manuals
std::forward: std::forward
NAME
Synopsis
Defined in header <utility>
template< class T > (1) (since C++11)
T&& forward( typename std::remove_reference<T>::type& t ) noexcept; (until C++14)
template< class T > (1) (since C++14)
constexpr T&& forward( typename std::remove_reference<T>::type& t ) noexcept;
template< class T > (2) (since C++11)
T&& forward( typename std::remove_reference<T>::type&& t ) noexcept; (until C++14)
template< class T > (2) (since C++14)
constexpr T&& forward( typename std::remove_reference<T>::type&& t ) noexcept;
1) Forwards lvalues as either lvalues or as rvalues, depending on T
When t is a forwarding_reference (a function argument that is declared as an rvalue reference to a cv-unqualified function template parameter), this overload forwards the argument to another function with the value_category it had when passed to the calling function.
For example, if used in wrapper such as the following, the template behaves as described below:
* If a call to wrapper() passes an rvalue std::string, then T is deduced to std::string (not std::string&, const std::string&, or std::string&&), and std::forward ensures that an rvalue reference is passed to foo.
* If a call to wrapper() passes a const lvalue std::string, then T is deduced to const std::string&, and std::forward ensures that a const lvalue reference is passed to foo.
* If a call to wrapper() passes a non-const lvalue std::string, then T is deduced to std::string&, and std::forward ensures that a non-const lvalue reference is passed to foo.
2) Forwards rvalues as rvalues and prohibits forwarding of rvalues as lvalues
This overload makes it possible to forward a result of an expression (such as function call), which may be rvalue or lvalue, as the original value category of a forwarding reference argument.
For example, if a wrapper does not just forward its argument, but calls a member function on the argument, and forwards its result:
where the type of arg may be
Attempting to forward an rvalue as an lvalue, such as by instantiating the form (2) with lvalue reference type T, is a compile-time error.
Notes
See template_argument_deduction for the special rules behind forwarding references (T&& used as a function parameter) and forwarding_references for other detail.
Parameters
t - the object to be forwarded
Return value
static_cast<T&&>(t)
Example
This example demonstrates perfect forwarding of the parameter(s) to the argument of the constructor of class T. Also, perfect forwarding of parameter packs is demonstrated.
// Run this code
Output:
Complexity
Constant
See also
move obtains an rvalue reference
(C++11)
move_if_noexcept obtains an rvalue reference if the move constructor does not throw
(C++11)