views:

239

answers:

2

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  A: 

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.

Blindy
is `vv` required? Will the inner lamdba work without?
caspin
+5  A: 
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.

DeadMG
Thanks for the workaround, hopefully this will be fixed in a later version.
DanDan