Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialization by lambda expression in c++

Tags:

c++

lambda

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?

like image 236
stamaimer Avatar asked Dec 25 '22 12:12

stamaimer


1 Answers

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.

like image 89
Mark Garcia Avatar answered Jan 06 '23 09:01

Mark Garcia