Do we have closures in C++?

前端 未结 6 580
慢半拍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:42

    If you understand closure as a reference to a function that has an embedded, persistent, hidden and unseparable context (memory, state), then yes:

    class add_offset {
    private:
        int offset;
    public:
        add_offset(int _offset) : offset(_offset) {}
        int operator () (int x) { return x + offset; }
    }
    
    // make a closure
    add_offset my_add_3_closure(3);
    
    // use closure
    int x = 4;
    int y = my_add_3_closure(x);
    std::cout << y << std::endl;
    

    The next one modifies its state:

    class summer
    {
    private:
        int sum;
    public:
        summer() : sum(0) {}
        int operator () (int x) { return sum += x; }
    }
    
    // make a closure
    summer adder;
    // use closure
    adder(3);
    adder(4);
    std::cout << adder(0) << std::endl;
    

    The inner state can not be referenced (accessed) from outside.

    Depending on how you define it, a closure can contain a reference to more than one function or, two closures can share the same context, i.e. two functions can share the same persistent state.

    Closure means not containing free variables - it is comparable to a class with only private attributes and only public method(s).

提交回复
热议问题