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++?
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).