4

i write follow code:

static int count = []()->int
                   {
                       int count = 0;

                       for(int i = 0; i < categories.size(); ++i)
                       {
                           if(!categories[i].isCategory())
                           {
                               count++;
                           }
                       }

                       return count;
                   };

and got error:error: cannot convert '__lambda0' to 'int' in initialization.

does the meaning of my code fragment is assign the __lambda0 to static int count instead of return the inner count?

1
  • 1
    Yes, you're assigning the lambda (function), not its evaluation. You need to actually invoke the lambda. Commented Feb 28, 2014 at 7:12

2 Answers 2

8

You aren't calling it! Make sure you do so:

static int count = []()->int
                   {
                       int count = 0;

                       for(int i = 0; i < categories.size(); ++i)
                       {
                           if(!categories[i].isCategory())
                           {
                               count++;
                           }
                       }

                       return count;
                   }();
                 // ^^ THIS THIS THIS THIS

BUT, IMHO, you're better off in this without using a lambda. And in the case where you'd use it in other parts of your code, then have it in a stand-alone (not lambda) function.

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is a valid use-case. It might be a static local, and the lambda could depend on other locals. (But this example doesn't show anything get captured.)
2

does the meaning of my code fragment is assign the __lambda0 to static int count instead of return the inner count?

Exactly. To call the lambda, just add () at the end.

                   …
               } ();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.