[英]Closure and nested lambdas in C++0x
使用C ++ 0x,當我在lambda中有lambda時如何捕獲變量? 例如:
std::vector<int> c1;
int v = 10; <--- I want to capture this variable
std::for_each(
c1.begin(),
c1.end(),
[v](int num) <--- This is fine...
{
std::vector<int> c2;
std::for_each(
c2.begin(),
c2.end(),
[v](int num) <--- error on this line, how do I recapture v?
{
// Do something
});
});
std::for_each(
c1.begin(),
c1.end(),
[&](int num)
{
std::vector<int> c2;
int& v_ = v;
std::for_each(
c2.begin(),
c2.end(),
[&](int num)
{
v_ = num;
}
);
}
);
不是特別干凈,但確實有效。
我能想到的最好的是:
std::vector<int> c1;
int v = 10;
std::for_each(
c1.begin(),
c1.end(),
[v](int num)
{
std::vector<int> c2;
int vv=v;
std::for_each(
c2.begin(),
c2.end(),
[&](int num) // <-- can replace & with vv
{
int a=vv;
});
});
有趣的問題! 我會睡在上面,看看我能不能找到更好的東西。
在內部lambda中你應該有(假設你想通過引用傳遞變量):
[&v](int num)->void{
int a =v;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.