Was mache ich falshc bei lambdas?



  • Hi,

    folgender code kompiliert nicht (MSVC++2010):

    BOOST_FOREACH(const auto i, gate.ipc)
    {
    if(std::find_if(outputs.cbegin(),outputs.cend(),[i.first](const std::string &str) { return str== i.first; }) != outputs.cend())
    {
    // mach was 
    }
    }
    

    Der folgende kompiliert, warum muss ich ich den member first von i erst x zuweisen, damit es kompiliert?

    BOOST_FOREACH(const auto i, gate.ipc)
    {
    
    auto x = i.first;
    if(std::find_if(outputs.cbegin(),outputs.cend(),[&x](const std::string &str) { return str== x; }) != outputs.cend())
    {
    // mach was 
    }
    }
    

    Die Fehler die ich bekomme sind:

    >main.cpp(126): error C2143: syntax error : missing ']' before '.'
    1>main.cpp(126): error C2059: syntax error : ']'
    1>main.cpp(126): error C2059: syntax error : '.'
    1>main.cpp(126): error C2143: syntax error : missing ';' before '{'
    1>main.cpp(126): error C2065: 'str' : undeclared identifier
    1>main.cpp(126): error C2059: syntax error : ')'
    

    Und noch viel mehr



  • [i.first](const std::string &str) { return str== i.first; }) != outputs.cend()
    

    Das machst du falsch. Lambdas werden wie normale Funktionen durch } abgeschlossen. Was soll der Rest?



  • i.first ist keine Variable, die Du "capturen" kannst. Warum nimmst Du nicht das ganze i ?



  • Furble Wurble schrieb:

    i.first ist keine Variable, die Du "capturen" kannst. Warum nimmst Du nicht das ganze i ?

    Danke, das war der Fehler! 🙂 Aber wieso kann ich das i.first nicht "capturen" ?



  • MokuYobi schrieb:

    Furble Wurble schrieb:

    i.first ist keine Variable, die Du "capturen" kannst. Warum nimmst Du nicht das ganze i ?

    Danke, das war der Fehler! 🙂 Aber wieso kann ich das i.first nicht "capturen" ?

    i.first ist a) keine Variable und wird b) nicht im Scope des Lambda deklariert.
    i schon.


  • Mod

    Aber wieso kann ich das i.first nicht "capturen" ?

    Es ist ein Subobjekt. Du kannst nur komplette Objekte capturen.

    b) nicht im Scope des Lambda deklariert.

    Das Argument ist fast richtig:

    If a lambda-expression captures an entity and that entity is not defined [...] in the immediately enclosing [...] function, the program is ill-formed.


Anmelden zum Antworten