为什么第二次调用会f()导致编译错误:
lambda 闭包无法转换为 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
}
Run Code Online (Sandbox Code Playgroud)
因为你忘记了return:
f([](int x, int y = 10) { return g(x,y); }, 20);\nRun Code Online (Sandbox Code Playgroud)\n如果没有return,您的 lambda 不会\xe2\x80\x99 返回值,并且 C++ 会推断void返回类型。