Vin*_*ent 6 c++ lambda perfect-forwarding c++11 universal-reference
考虑以下两点:
template <class Function>
void apply(Function&& function)
{
std::forward<Function>(function)();
}
Run Code Online (Sandbox Code Playgroud)
和
template <class Function>
void apply(Function&& function)
{
function();
}
Run Code Online (Sandbox Code Playgroud)
在什么情况下有差异,它有什么具体的区别?
Man*_*rse 12
还有,如果一个差Function的operator()已REF预选赛.使用std::forward,传播参数的值类别,如果没有它,则值类别将丢失,并且函数将始终作为l值调用.实例.
#include <iostream>
struct Fun {
void operator()() & {
std::cout << "L-Value\n";
}
void operator()() && {
std::cout << "R-Value\n";
}
};
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-Value\n"
apply_forward(Fun{}); // Prints "R-Value\n"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |