簡體   English   中英

無需聲明和初始化的類似閉包的函數(即不使用“ auto f = make_closure();”)

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

C ++中閉包的典型示例如下:

[code1]

#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

[code2]

#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]中的f完全相同。 和[代碼1]之間的差[碼2]是,在[code2產生]我們沒有聲明和初始化f通過auto f = make_closure();

並非完全相同,但是您將獲得與以下相同的輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM