gpt4 book ai didi

c++ - Lambda 闭包无法转换为 std::function

转载 作者:行者123 更新时间:2023-12-03 07:11:56 25 4
gpt4 key购买 nike

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

lambda closure cannot be converted into std::function<int(int)>

#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
}

最佳答案

因为您忘记了返回:

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

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

关于c++ - Lambda 闭包无法转换为 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64731103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com