1

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.

Troskyvs
  • 7,537
  • 7
  • 47
  • 115

2 Answers2

2

(1) It converts the lambda with no capture to function pointer.

(2) It indicates that you are about to capture by value, in which case conversion to function pointer is not possible.

lorro
  • 10,687
  • 23
  • 36
2

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770