考虑以下两个片段:
附件 A:
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
}
图表 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
}
差异:
precalc();
- int const calc = calcfunc();
+ int const calc = std::forward<CalcFuncT>(calcfunc)();
postcalc();
这两段代码生成的代码有什么区别(如果有的话)?
换句话说,上面的 std::forward 有什么影响,如果有的话?
请注意,这个问题并不是在询问 std::forward 一般情况下的作用 - 而是在上述上下文中的作用?
最佳答案
forward
在调用 operator()() 之前将 lambda 对象转换为一个 xvalue。 lambda 对象的 operator()() 没有限定或重载“&&”,因此 forward
应该没有影响。
关于c++ - std::forward of rvalue ref to lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9917027/