代码之家  ›  专栏  ›  技术社区  ›  HiroIshida

没有声明和初始化的类闭包函数(即没有“auto f=make_Closure();”)

  •  -1
  • HiroIshida  · 技术社区  · 7 年前

    C++中的一个典型例子如下:

    #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 如下图所示:

    #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]中,我们不必声明和初始化 F auto f = make_closure(); .

    1 回复  |  直到 7 年前
        1
  •  3
  •   Jarod42    7 年前

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