【问题标题】:Closure-like function without declaration and intialization (i.e. without `auto f = make_closure();`)没有声明和初始化的类闭包函数(即没有`auto f = make_closure();`)
【发布时间】: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

【问题讨论】:

    标签: c++ lambda closures


    【解决方案1】:

    并不完全相同,但你会得到相同的输出:

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

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多