Lambda closure cannot be converted to std::function

Viewed 122

Why does the second call to f() result in a compilation-error:

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
}
1 Answers

Because you forgot a return:

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

Without return, your lambda doesn’t return a value, and C++ infers a void return type.

Related