Using volume variables in C ++ 11 lambda expressions

I play with C ++ 11 for fun. I am wondering why this is happening:

//... std::vector<P_EndPoint> agents; P_CommunicationProtocol requestPacket; //... bool repeated = std::any_of(agents.begin(), agents.end(), [](P_EndPoint i)->bool {return requestPacket.identity().id()==i.id();}); 

Compilation fails with this error:

 error: 'requestPacket' has not been declared 

What is declared earlier in the code. I tried ::requestPacke and it didn't work either.

How to use an external scope variable inside a lambda function?

+7
source share
1 answer

You need to capture a variable , either by value (using the syntax [=] )

 bool repeated = std::any_of(agents.begin(), agents.end(), [=](P_EndPoint i)->bool {return requestPacket.identity().id()==i.id();}); 

or by reference (using the syntax [&] )

 bool repeated = std::any_of(agents.begin(), agents.end(), [&](P_EndPoint i)->bool {return requestPacket.identity().id()==i.id();}); 

Please note that, as @aschepler points out, global variables with static storage duration are not fixed , only function level variables:

 #include <iostream> auto const global = 0; int main() { auto const local = 0; auto lam1 = [](){ return global; }; // global is always seen auto lam2 = [&](){ return local; }; // need to capture local std::cout << lam1() << "\n"; std::cout << lam2() << "\n"; } 
+24
source

All Articles