std::通过通用引用传递的函数的转发
std::forward of a function passed via universal reference?
考虑以下两个:
template <class Function>
void apply(Function&& function)
{
std::forward<Function>(function)();
}
和
template <class Function>
void apply(Function&& function)
{
function();
}
在什么情况下会有区别,具体区别是什么?
如果Function
的operator()
具有ref限定符,则会有所不同。有了std::forward
,参数的值类别就会传播,没有它,值类别就会丢失,函数将始终作为l-value调用。活生生的例子。
#include <iostream>
struct Fun {
void operator()() & {
std::cout << "L-Valuen";
}
void operator()() && {
std::cout << "R-Valuen";
}
};
template <class Function>
void apply(Function&& function) {
function();
}
template <class Function>
void apply_forward(Function&& function) {
std::forward<Function>(function)();
}
int main () {
apply(Fun{}); // Prints "L-Valuen"
apply_forward(Fun{}); // Prints "R-Valuen"
}
相关文章:
- 将函数参数完美转发到函数指针:按值传递呢?
- 在按值调用 (c++) 中转发构造函数参数
- 使用函数指针转发声明作为 lamba 声明
- 完美的转发和构造函数
- 我可以在构造函数的主体中转发构造吗?
- 通过类型别名从构造函数转发模板推导
- 在可变参数函数中转发特定范围的参数
- 为什么添加析构函数(甚至是空的)会破坏我的结构,该结构使用 ref 转发和折叠来保存 ref 或值的副本?
- 如何在程序集函数中将元素数组作为参数传递时转发 ARM 寄存器的地址指针
- 如何通过可变参数模板将多个构造函数参数转发到数组初始值设定项列表?
- 类似函数的化简函数中的转发和返回类型
- 在编写包装现有函数并检查错误的模板函数时,如何使用完美转发?
- 将可变参数函数参数转发到 std::function 对象
- 将转发 lambda 转换为函数指针
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++中的友元成员函数 - 转发声明不起作用
- 将构造函数转发到成员对象
- 通过函数转发常量引用
- 函数转发参数而不执行任何操作
- 将参数从可变参数函数转发到固定参数函数