问题
Using C++0x, how do I capture a variable when I have a lambda within a lambda? For example:
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
});
});
回答1:
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;
}
);
}
);
Not especially clean, but it does work.
回答2:
The best I could come up with is this:
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;
});
});
Interesting problem! I'll sleep on it and see if i can figure something better out.
回答3:
In the inner lambda you should have(assuming you want to pass the variable by reference):
[&v](int num)->void{
int a =v;
}
来源:https://stackoverflow.com/questions/2891690/closure-and-nested-lambdas-in-c0x