在C ++ 11 lambda表达式中使用超出范围的变量 [英] using out of scope variables in C++11 lambda expressions
本文介绍了在C ++ 11 lambda表达式中使用超出范围的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在玩C ++ 11。我想知道为什么会这样:
I'm playing with C++11 for fun. I'm wondering why this happens:
//...
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 terminates with this error:
error: 'requestPacket' has not been declared
已声明较早的代码。我尝试了 :: requestPacke
,它也无法正常工作。
Which is declared earlier in code. I tried ::requestPacke
and it doesn't worked too.
如何在内部使用外部范围变量Lambda函数?
How can I use an external scope variable inside a lambda function?
推荐答案
您需要变量,按值(使用 [=]
语法)
You need to capture the 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();});
请注意,正如@aschepler指出的那样,未捕获具有静态存储持续时间的全局变量,仅捕获了函数级变量:
Note that as @aschepler points out, global variables with static storage duration are not captured, 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";
}
这篇关于在C ++ 11 lambda表达式中使用超出范围的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文