首页 C++系列21:forward
文章
取消

C++系列21:forward

每天学点C++

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
28
29
30
31
32
33
34
35
36
37
38
用于转发,通常与模板函数和右值引用一起使用

完美转发函数参数:在模板函数中,将参数转发给另一个函数,同时保持其值类别(左值或右值)。

语法:
template <class T>
T&& forward(typename std::remove_reference<T>::type& t) noexcept;

示例

#include <iostream>
#include <utility>

void process(int& x) {
std::cout << "Lvalue reference: " << x << std::endl;
}

void process(int&& x) {
std::cout << "Rvalue reference: " << x << std::endl;
}

template <typename T>
void forwarder(T&& arg) {
process(std::forward<T>(arg));
}

int main() {
int a = 10;
forwarder(a);        // 调用 process(int&)
forwarder(20);       // 调用 process(int&&)
return 0;
}

T&& 是一种特殊的类型称为 转发引用(forwarding reference),
也称为 万能引用(universal reference)。
它允许模板函数能够接受左值和右值,并保持它们的值类别。
也就是说即可以接受左值,也可以接受右值。

欢迎评论交流

本文由作者按照 CC BY 4.0 进行授权