Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure and nested lambdas in C++0x

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
            });
    });
like image 695
DanDan Avatar asked May 23 '10 12:05

DanDan


2 Answers

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.

like image 104
Puppy Avatar answered Oct 19 '22 14:10

Puppy


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.

like image 26
Blindy Avatar answered Oct 19 '22 13:10

Blindy