【问题标题】:Lambda closure cannot be converted to std::functionLambda 闭包无法转换为 std::function
【发布时间】:2021-02-20 03:50:33
【问题描述】:

为什么第二次调用f() 会导致编译错误:

lambda 闭包不能转换为 std::function

#include <vector>
#include <functional>

void f(std::function<int(int)>f1, int x) {
    f1(x);
}

int g(int x, int y) {
    std::cout << x + y;
    return x;
}

int main() {
    f([](int x, int y = 10){ std::cout << x + y; return x; }, 20); // this works
    f([](int x, int y = 10){ g(x,y); }, 20); // this doesn't compile
}

【问题讨论】:

  • 您是否记得是否需要使用特定的 C++ 关键字才能从函数中返回一个值?你的闭包返回什么值,它们的类型是什么?

标签: c++ c++11 lambda


【解决方案1】:

因为你忘记了return

f([](int x, int y = 10) { return g(x,y); }, 20);

没有return,您的lambda 不会返回值,C++ 会推断出void 返回类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2016-04-18
    • 2012-06-25
    相关资源
    最近更新 更多