Trivia impact: rare
The Lambda That Becomes a Function Pointer
a local callable accepted where an ordinary callback is required
using Callback = int (*)(int);
Callback callback = [](int value) { return value * 2; };
std::cout << callback(21) << "\n";
Does this compile? What does it print?
Why¶
[expr.prim.lambda.closure] gives a non-generic lambda with no captures a conversion
function to a pointer to function with the same parameter and return types as its call
operator. The converted pointer calls a generated function with the same effect as the
lambda's operator(), so assigning this lambda to Callback is well-formed. A lambda
that captures a local has state in its closure and cannot use this conversion.
Where it shows up¶
Some callback APIs take a literal pointer-to-function type instead of an arbitrary callable. A captureless lambda is a tidy adapter at that boundary; state still has to go through whatever context mechanism that API provides. Most modern C++ callback APIs are templates or type-erased callables, so this is useful but not everyday code.
Takeaway: a captureless non-generic lambda can convert to a matching function pointer.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo