std::forward

转自:https://riptutorial.com/cplusplus/example/3898/argument-forwarding

std::forward 用于传递一个或者多个参数给函数

Example#

Template may accept both lvalue and rvalue references using forwarding reference:

template <typename T>
void f(T &&t);

In this case, the real type of t will be deduced depending on the context:

struct X { };

X x;
f(x); // calls f<X&>(x)
f(X()); // calls f<X>(x)

In the first case, the type T is deduced as reference to X (X&), and the type of t is lvalue reference to X, while in the second case the type of T is deduced as X and the type of t as rvalue reference to X (X&&).

Note: It is worth noticing that in the first case, decltype(t) is the same as T, but not in the second.

In order to perfectly forward t to another function ,whether it is an lvalue or rvalue reference, one must use std::forward:

template <typename T>
void f(T &&t) {
    g(std::forward<T>(t));
}

Forwarding references may be used with variadic templates:

template <typename... Args>
void f(Args&&... args) {
    g(std::forward<Args>(args)...);
}

Note: Forwarding references can only be used for template parameters, for instance, in the following code, v is a rvalue reference, not a forwarding reference:

#include <vector>

template <typename T>
void f(std::vector<T> &&v);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值