【发布时间】:2019-01-24 13:01:25
【问题描述】:
一个典型的c++闭包例子如下:
[代码1]
#include <iostream>
#include <functional>
std::function<void()> make_closure(){
int i = 0;
return [=]() mutable -> void{i++; std::cout << i << std::endl;};
}
int main(){
auto f = make_closure();
for (int i=0; i<10; i++) f();
}
这将在命令行中显示 1, 2, .... 10。现在,我很好奇如何在没有声明和初始化的情况下制作一个类似闭包的函数,更准确地说是函数f,如下所示:
[代码2]
#include <iostream>
void f(){
//some code ... how can I write such a code here?
}
int main(){
for(int i=0; i<10; i++) f();
}
此代码中的f 与[code1] 中的工作方式完全相同。 [code1] 和 [code2] 的区别在于,在 [code2] 中我们不必通过auto f = make_closure(); 声明和初始化f。
【问题讨论】: