C++ Utility 库 - forward 函数
描述
如果 arg 不是左值引用,则返回对 arg 的右值引用。
声明
以下是 std::forward 函数的声明。
template <class T> T&& forward (typename remove_reference<T>::type& arg) noexcept; template <class T> T&& forward (typename remove_reference<T>::type&& arg) noexcept;
C++11
template <class T> T&& forward (typename remove_reference<T>::type& arg) noexcept; template <class T> T&& forward (typename remove_reference<T>::type&& arg) noexcept;
参数
arg − 它是一个对象。
返回值
如果 arg 不是左值引用,则返回对 arg 的右值引用。
异常
Basic guarantee − 此函数从不抛出异常。
数据竞争
none
示例
在下面的示例中解释了 std::forward 函数。
#include <utility>
#include <iostream>
void overloaded (const int& x) {std::cout << "[It is a lvalue]";}
void overloaded (int&& x) {std::cout << "[It is a rvalue]";}
template <class T> void fn (T&& x) {
overloaded (x);
overloaded (std::forward<T>(x));
}
int main () {
int a;
std::cout << "calling fn with lvalue: ";
fn (a);
std::cout << '\n';
std::cout << "calling fn with rvalue: ";
fn (0);
std::cout << '\n';
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
calling fn with lvalue: [It is a lvalue][It is a lvalue] calling fn with rvalue: [It is a lvalue][It is a rvalue]

