Let's remove the syntactic sugar that the lambda functions provide us:
struct lambda1 {
void operator () {
std::cout << "Lambda 1!" << std::endl;
}
};
struct lambda2 {
void operator () {
std::cout << "Lambda 2!" << std::endl;
}
};
int main(int argc, char *argv[]) {
auto l1 = Lambda1{};
auto l2 = Lambda2{};
auto l1p = &l1; // l1p is a Lambda1 *
l1p = &l2; // &l2 is a Lambda2 *
return 0;
}
This isn't the exact transformation done by the compiler, but I think it suffices to examine the issue:
The two lambdas have each an own type, that is totally unrelated to their arguments, captured variables or return type. And of course, the types of lambdas are to each other unrelated, so you can obviously not assign a pointer to one from the address of the other.
The solution in the other answer with the function pointer is pretty nice. If there weren't a "you only pay for it when you use it" doctrine for C++, we could have made lambda functions like
struct SomeLambda
: public LambdaBase<
Capture<int>,
Arguments<bool>,
Return<void>> {
// ...
};
/*
[integer]
(bool flag) {
if (flag) cout << integer;
}
*/
But for that to make any sense the base would need to be polymorphic (has a virtual member function), and that's a cost you don't need if you don't intend to do what you wanted.