c++ - 在C ++ 11 lambda表达式中使用超出范围变量

我玩的是C++ 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

这是在代码前面声明的。我试过了,但效果不太好。
如何在lambda函数内使用外部作用域变量?


最佳答案:

您需要按值(使用[=]语法)输入capture the variable

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

注意,正如@aschepler指出的,只有函数级变量:
#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";
}