2010-05-23 45 views
13

使用C++ 0x时,如何在lambda内使用lambda时捕获变量?例如:C++中的闭包和嵌套lambdas 0x

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

我猜分配在第一关闭可能会帮助该变量。 – 2010-05-23 12:34:14

+3

以上在gcc4.5上很好 - 你使用VC10吗? – 2010-05-23 12:47:26

+1

是的,VC10。我会把它报告给微软。 – DanDan 2010-05-23 12:51:28

回答

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

不是特别干净,但它确实有效。

+0

感谢您的解决方法,希望这将在更高版本中得到修复。 – DanDan 2010-05-23 13:05:11

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

是否需要'vv'?内部的灵堂工作没有? – 2010-05-24 15:39:22

0

在你应该有内部的λ(假设你想通过引用传递变量):

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

    int a =v; 
}