C++0x中的闭包和嵌套lambda函数

14

在使用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
            });
    });

我猜在第一个闭包中分配变量可能会有所帮助。 - Gabriel Ščerbák
3
上面在gcc4.5上没问题 - 你是在用VC10吗? - Georg Fritzsche
1
是的,VC10。我会向微软报告。 - DanDan
听起来不错,我看不出为什么这行不通。 - Georg Fritzsche
1
微软连接记录(Microsoft Connect entry):捕获嵌套 Lambda 中的变量。 - Georg Fritzsche
显示剩余3条评论
3个回答

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;
                }
            );
        }
    );

虽然不是十分干净,但它确实起作用。


感谢您的解决方法,希望这个问题能在以后的版本中得到修复。 - DanDan

1
我能想到的最好的是这个:
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;
            });
    });

有趣的问题!我会好好想一想,看看能否找到更好的解决方案。


0
在内部 lambda 中,您应该有以下内容(假设您想通过引用传递变量):
[&v](int num)->void{

  int a =v;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接