函式模板
<utility>

std::forward

左值 (1)
template <class T> T&& forward (typename remove_reference<T>::type& arg) noexcept;
右值 (2)
template <class T> T&& forward (typename remove_reference<T>::type&& arg) noexcept;
轉發引數
如果 arg 不是左值引用,則返回 arg 的右值引用。

如果 arg 是左值引用,則函式在不修改其型別的情況下返回 arg

這是一個輔助函式,用於將作為右值引用的引數完美轉發給推匯出的型別,保留其中可能存在的移動語義。

需要此函式是因為所有命名值(例如函式引數)都始終評估為左值(即使是宣告為右值引用的),這在保留模板函式中對其他函式的引數的潛在移動語義方面存在困難。

兩個簽名都返回相同的
1
static_cast<decltype(arg)&&>(arg)

透過提供兩個簽名並對 T 使用 remove_reference,可以強制任何例項化顯式指定 T 的型別(任何隱式推導的 T 都將不匹配)。

引數

arg
一個物件。

返回值

如果 arg 是左值引用,則函式返回的 arg 的型別保持不變。
否則,函式返回一個右值引用(T&&),該引用指向 arg,可用於傳遞右值。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// forward example
#include <utility>      // std::forward
#include <iostream>     // std::cout

// function with lvalue and rvalue reference overloads:
void overloaded (const int& x) {std::cout << "[lvalue]";}
void overloaded (int&& x) {std::cout << "[rvalue]";}

// function template taking rvalue reference to deduced type:
template <class T> void fn (T&& x) {
  overloaded (x);                   // always an lvalue
  overloaded (std::forward<T>(x));  // rvalue if argument is rvalue
}

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: [lvalue][lvalue]
calling fn with rvalue: [lvalue][rvalue]


資料競爭



異常

無異常保證:此函式從不丟擲異常。

另見