c++ - std::forward of rvalue ref to lambda?

标签 c++ lambda c++11 forwarding rvalue-reference

考虑以下两个片段:

附件 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/

相关文章:

具有非静态成员初始值设定项的类的 C++11 聚合初始化

c++ - LLVM 5.0中如何从TargetMachine获取DataLayout?

c++ - 从 fstream 读取单个字符?

java - 了解 lambda 和/或谓词

javascript - 当从异步函数返回 Promise 时会发生什么?

java.lang.NullPointerException 使用方法引用而不是 lambda 表达式引发

c++11 - 将元素插入 lambda 函数内的向量时出错

C++如何制作这种构造函数的原型(prototype)?

c++ - 使用 libCurl 和 JsonCpp 从 https 网络服务器解析

c++ - 为什么使用自定义对话框会得到 "QMetaObject::connectSlotsByName: No matching signal"?