And*_*zos 5 c++ lambda forwarding rvalue-reference c++11
考虑以下两个片段:
附件一:
template<typename CalcFuncT>
int perform_calc(CalcFuncT&& calcfunc)
{
precalc();
int const calc = calcfunc();
postcalc();
return calc;
}
int main()
{
perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture
perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast
}
Run Code Online (Sandbox Code Playgroud)
附件B:
template<typename CalcFuncT>
int perform_calc(CalcFuncT&& calcfunc)
{
precalc();
int const calc = std::forward<CalcFuncT>(calcfunc)();
postcalc();
return calc;
}
int main()
{
perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture
perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast
}
Run Code Online (Sandbox Code Playgroud)
差异:
precalc();
- int const calc = calcfunc();
+ int const calc = std::forward<CalcFuncT>(calcfunc)();
postcalc();
Run Code Online (Sandbox Code Playgroud)
这两段代码生成的代码有什么区别(如果有的话)?
换句话说,上面的 std::forward 有什么作用(如果有的话)?
请注意,这个问题并不是问 std::forward 一般做什么——只是问它在上述上下文中做什么?
在调用 lambda 对象的 operator()() 之前,将forward其转换为 xvalue。lambda 对象的 operator()() 未使用“&&”限定或重载,因此应该forward没有影响。