没有声明和初始化的类似闭包的函数(即没有'auto f = make_closure();')
Closure-like function without declaration and intialization (i.e. without `auto f = make_closure();`)
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();
}
相关文章:
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- make 命令如何避免重新编译未更改的源文件?
- MAKE:找不到包含的用户定义的头文件?
- 'make check' GLIBC 运行时的链接问题
- Qt5 [make -snap] 无法正确编译:进程"/usr/bin/snap"代码 1 退出
- mingw32-make 使用"MinGW Makefiles"生成器跟踪 CMAKE 无法将可执行文件链接到对象库
- make 命令创建 .file,但不创建应用程序文件
- 如何摆脱导入的 make 项目中的 Eclipse 索引器"Type std::... could not be resolved"错误
- Qt Creator 在执行步骤 "make" 时出现编译错误,-fno-stack-limit
- 如何使用MySQL Connector and Make设置C++项目
- 使用 make 将对象文件放在特定目录中
- 我是 C++ 的新手,我试图调用 make 一个以 2 个类作为其参数的类构造函数
- "Make"失败并出现 Clang 错误 - 如何从 Clang 获得错误?
- 防止 GNU Make 在每次构建时生成 protobuf 代码
- Make zmqpp::socket::connect a std::future
- 链接从命令行转换为Make的库
- 将 make 和 cmake 合并到构建系统中
- 使用 CMake (make) 和 GCC 构建和编译 gSOAP 项目
- Cassandra C++ MacOS High Sierra上的驱动程序:make:没有规则来制作目标