std::forward
| 定义于头文件 <utility>
|
||
template< class T >
T&& forward( typename std::remove_reference<T>::type& t ) noexcept;
|
(1) | (C++11 起) (C++14 前) |
template< class T >
constexpr T&& forward( std::remove_reference_t<T>& t ) noexcept;
|
(C++14 起) | |
template< class T >
T&& forward( typename std::remove_reference<T>::type&& t ) noexcept;
|
(2) | (C++11 起) (C++14 前) |
template< class T >
constexpr T&& forward( std::remove_reference_t<T>&& t ) noexcept;
|
(C++14 起) | |
当t是一个转发引用(声明为指向无 cv 限定函数模板参数的右值引用的函数参数)时,此重载将参数以传递给调用函数时的值类别转发给另一个函数。
例如,如果在如下所示的包装器中使用,该模板的行为如下所述:
template<class T>
void wrapper(T&& arg)
{
// arg is always lvalue
foo(std::forward<T>(arg)); // Forward as lvalue or as rvalue, depending on T
}
- 如果对
wrapper()的调用传入一个右值std::string,那么T被推导为std::string(不是std::string&、const std::string&或std::string&&),且std::forward确保将右值引用传递给foo。 - 如果对
wrapper()的调用传入一个 const 左值std::string,那么T被推导为const std::string&,且std::forward确保将 const 左值引用传递给foo。 - 如果对
wrapper()的调用传入一个非 const 左值std::string,那么T被推导为std::string&,且std::forward确保将非 const 左值引用传递给foo。
此重载使得可以将表达式(如函数调用)的结果(可能是右值或左值)作为转发引用参数的原始值类别进行转发。
例如,如果包装器不仅仅转发其参数,而是对参数调用成员函数并转发其结果:
// transforming wrapper
template<class T>
void wrapper(T&& arg)
{
foo(forward<decltype(forward<T>(arg).get())>(forward<T>(arg).get()));
}
其中 arg 的类型可以是
struct Arg
{
int i = 1;
int get() && { return i; } // call to this overload is rvalue
int& get() & { return i; } // call to this overload is lvalue
};
尝试将右值转发为左值,例如通过使用左值引用类型 T 实例化形式 (2),会导致编译时错误。
注释
请参阅
模板实参推导
了解转发引用(函数参数中使用的
T&&
)背后的特殊规则,以及
转发引用
获取其他详细信息。
参数
| t | - | 待转发的对象 |
返回值
static_cast < T && > ( t )
复杂度
常量。
示例
本示例演示了如何将参数完美转发给类
T
构造函数的实参。同时展示了参数包的完美转发。
#include <iostream> #include <memory> #include <utility> struct A { A(int&& n) { std::cout << "rvalue overload, n=" << n << '\n'; } A(int& n) { std::cout << "lvalue overload, n=" << n << '\n'; } }; class B { public: template<class T1, class T2, class T3> B(T1&& t1, T2&& t2, T3&& t3) : a1_{std::forward<T1>(t1)}, a2_{std::forward<T2>(t2)}, a3_{std::forward<T3>(t3)} {} private: A a1_, a2_, a3_; }; template<class T, class U> std::unique_ptr<T> make_unique1(U&& u) { return std::unique_ptr<T>(new T(std::forward<U>(u))); } template<class T, class... U> std::unique_ptr<T> make_unique2(U&&... u) { return std::unique_ptr<T>(new T(std::forward<U>(u)...)); } auto make_B(auto&&... args) // since C++20 { return B(std::forward<decltype(args)>(args)...); } int main() { auto p1 = make_unique1<A>(2); // rvalue int i = 1; auto p2 = make_unique1<A>(i); // lvalue std::cout << "B\n"; auto t = make_unique2<B>(2, i, 3); std::cout << "make_B\n"; [[maybe_unused]] B b = make_B(4, i, 5); }
输出:
rvalue overload, n=2 lvalue overload, n=1 B rvalue overload, n=2 lvalue overload, n=1 rvalue overload, n=3 make_B rvalue overload, n=4 lvalue overload, n=1 rvalue overload, n=5
参见
|
(C++11)
|
将实参转换为亡值
(函数模板) |
|
(C++11)
|
若移动构造函数不抛出异常则将实参转换为亡值
(函数模板) |