没有声明和初始化的类似闭包的函数(即没有'auto f = make_closure();')

Closure-like function without declaration and intialization (i.e. without `auto f = make_closure();`)

本文关键字:make closure auto 闭包 函数 初始化 声明      更新时间:2023-10-16

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

不是很一样,但你会得到相同的输出:

#include<iostream>
#include<functional>
void f(){
    static int i = 0;
    i++;
    std::cout << i << std::endl;
}
int main(){
    for(int i=0; i<10; i++) f();
}