目录

forward

描述 (Description)

如果arg不是左值引用,则返回对arg的右值引用。

声明 (Declaration)

以下是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;

参数 (Parameters)

arg - 这是一个对象。

返回值 (Return Value)

如果arg不是左值引用,则返回对arg的右值引用。

异常 (Exceptions)

Basic guarantee - 此函数永远不会抛出异常。

数据竞争 (Data races)

没有

例子 (Example)

在下面的例子中解释了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]
↑回到顶部↑
WIKI教程 @2018