Closure and nested lambdas in C++0x
Asked Answered
A

3

15

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
            });
    });
Alcorn answered 23/5, 2010 at 12:23 Comment(8)
I would guess assigning the variable in the first closure might help.Turnbow
The above is fine on gcc4.5 - are you using VC10?Galley
Yes, VC10. I shall report it to Microsoft.Alcorn
Sounds good, i don't see why this shouldn't work.Galley
Especially since this works for VC#, wrote by the same company.Illtempered
Different team, different standard.Road
Microsoft Connect entry.Galley
Any idea if this is fixed? @AlcornEnamelware
R
8
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.

Road answered 23/5, 2010 at 12:35 Comment(1)
Thanks for the workaround, hopefully this will be fixed in a later version.Alcorn
I
1

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.

Illtempered answered 23/5, 2010 at 12:32 Comment(0)
N
0

In the inner lambda you should have(assuming you want to pass the variable by reference):

[&v](int num)->void{

  int a =v;
}
Nobe answered 12/4, 2011 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.