2010-09-10 87 views
0

基本上,我想知道如果像下面的东西是可能的?如果这是不可能的,有什么办法可以伪造它?有没有办法在不在当前范围内的lambda中使用变量?

#include <iostream> 
using namespace std; 

template<typename Functor> 
void foo(Functor func) 
{ 
    auto test = [](Functor f){ int i = 5; f(); }; 
    test(func); 
} 

int main() 
{ 
    foo([](){ cout << i << endl;}); 
} 
+1

为什么不让'i'成为一个参数? – kennytm 2010-09-10 17:31:32

+0

要么让我参数或我想找一个编译器,会做一些动态范围界定? – SubSevn 2010-09-10 17:33:51

+0

@KennyTM:我正在编写一个生成C++的小型编译器。我想用这样的东西来创建'let'语句。 – Ryan 2010-09-10 17:34:58

回答

1

您可以使i作为函数的参数。

#include <iostream> 
using namespace std; 

template<typename Functor> 
void foo(Functor func) 
{ 
    auto test = [](Functor f){ f(5); }; 
    test(func); 
} 

int main() 
{ 
    foo([](int i){ cout << i << endl;}); 
} 

否则,我认为你有一个范围是从两个地方,例如访问申报i作为全局变量:

#include <iostream> 
using namespace std; 

static int i; // <--- :(

template<typename Functor> 
void foo(Functor func) 
{ 
    auto test = [](Functor f){ i = 5; f(); }; 
    test(func); 
} 

int main() 
{ 
    foo([](){ cout << i << endl;}); 
} 
相关问题