Do we have closures in C++?

前端 未结 6 582
慢半拍i
慢半拍i 2020-12-13 02:19

I was reading about closures on the net. I was wondering if C++ has a built-in facility for closures or if there is any way we can implement closures in C++?

6条回答
  •  执笔经年
    2020-12-13 02:45

    Yes, This shows how you could implement a function with a state without using a functor.

    #include 
    #include 
    
    
    std::function make_my_closure(int x){
        return [x]() mutable {   
            ++x;
            return x;   
        };
    }
    
    int main()
    {
        auto my_f = make_my_closure(10);
    
        std::cout << my_f() << std::endl; // 11
        std::cout << my_f() << std::endl; // 12
        std::cout << my_f() << std::endl; // 13
    
         auto my_f1 = make_my_closure(1);
    
        std::cout << my_f1() << std::endl; // 2
        std::cout << my_f1() << std::endl; // 3
        std::cout << my_f1() << std::endl; // 4
    
        std::cout << my_f() << std::endl; // 14
    }
    

    I forgot the mutable keyword which introduced an undefined behaviour (clang version was returning a garbage value). As implemented, the closure works fine (on GCC and clang)

提交回复
热议问题