I've seen in stackoverflow, people write lambda like this:
int main() {
auto f1 = +[](){};
auto f2 = [](){};
return 0;
}
(1) What does the +
acturelly do in f1
expression?
I tried to add capture, then f1
doesn't compile, but the error is not readable to me:
auto f1 = +[=](){}; // fail to compile
auto f2 = [=](){};
The error is:
invalid argument type '(lambda at .\xxx.cpp:4:16)' to unary expression
auto f1 = +[=](){};
(2) What does this error indicate?
Thanks.
A lambda has a compiler-generated type. If you just assign the lambda as-is to an auto
variable, then the auto
variable's type will be deduced as the lambda's generated type.
A non-capturing lambda is implicitly convertible to a plain function pointer. By placing +
in front of the lambda, the lambda is explicitly converted to a function pointer, and then the auto
variable's type will be deduced as the function pointer type, not the lambda type.
A capturing lambda cannot be converted to a function pointer at all, which is why you get the compiler error.