PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] What does "+" mean in cpp lambda declaration "auto fun1 = +[](){};"

 November 04, 2022     c++, capture, compilation, lambda, types     No comments   

Issue

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.


Solution

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.



Answered By - Remy Lebeau
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing