2013-06-04 6 views
7

मैं मजेदार के लिए सी ++ 11 के साथ खेल रहा हूं। मैं सोच रहा हूँ कि ऐसा क्यों होता:सी ++ 11 लैम्ब्डा अभिव्यक्तियों में स्कोप चर के बाहर उपयोग करके

//... 
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();}); 

संकलन इस त्रुटि के साथ समाप्त हो जाता है:

error: 'requestPacket' has not been declared 

कौन सा कोड में पहले घोषित किया जाता है। मैंने ::requestPacke की कोशिश की और यह भी काम नहीं करता है।

मैं लैम्ब्डा फ़ंक्शन के अंदर बाहरी स्कोप चर का उपयोग कैसे कर सकता हूं?

+0

वे अंदर हैं एक वर्ग की एक विधि पक्ष। यह एक अच्छा खिताब नहीं है, शायद मुझे इसे 'मौजूदा दायरे से बाहर' में बदलना चाहिए ... –

उत्तर

24

आप या तो मूल्य से (का उपयोग कर [=] वाक्य रचना)

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

या संदर्भ द्वारा कि ([&] सिंटैक्स का उपयोग)

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

ध्यान दें, capture the variable की जरूरत @aschepler बताते हैं, global variables with static storage duration are not captured , केवल फ़ंक्शन-स्तरीय चर:

#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"; 
} 
+3

लैम्ब्डा कभी ग्लोबल्स पर कब्जा नहीं करते हैं, केवल फ़ंक्शन-स्थानीय चर। – aschepler

+1

टीएनएक्स, उत्तर अद्यतन किया गया। – TemplateRex

संबंधित मुद्दे