Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initialize variable with lambda

#include <iostream>

using namespace std;

int main()
{

    static bool temp([]{ 
        cout <<"Hi ";
        return false;});


   cout <<"temp "<< temp;

   return 0;
}

It does not execute lambda. But if we declare lambda separately like:

#include <iostream>

using namespace std;

int main()
{
    auto lambda = []{ 
        cout <<"Hi ";
        return false;};

    static bool temp(lambda());


   cout <<"temp "<< temp;

   return 0;
}

It will execute it. What am I missing here?

like image 769
debonair Avatar asked Dec 18 '19 01:12

debonair


1 Answers

You need to invoke the lambda, just as the 2nd code snippet does.

static bool temp([]{ 
    cout <<"Hi ";
    return false;}());
//                ^^

LIVE


PS: In the 1st code snippet temp will always be initialized as true, because lambda without capture list could convert to function pointer implicitly; which is a non-null pointer and then could convert to bool with value true.

like image 193
songyuanyao Avatar answered Nov 10 '22 16:11

songyuanyao