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++?
The C language does not have closure and that's because functions in C are not first-class objects. What this means is functions cannot be passed to other functions or cannot be returned from a function. What actually gets passed or returned is a pointer to it.
Some languages have features which simulate the behavior of closures. In languages such as Java, C++, Objective-C, C#, VB.NET, and D, these features are the result of the language's object-oriented paradigm.
In C++, lambda expression constructs a closure, an unnamed function object capable of capturing variables in scope. It still sounds ambiguous, at least to me. Closure is a general concept in programming that originated from functional programming.
Closure in Python is an inner function object, a function that behaves like an object, that remembers and has access to variables in the local scope in which it was created even after the outer function has finished executing.
The latest C++ standard, C++11, has closures.
http://en.wikipedia.org/wiki/C%2B%2B11#Lambda_functions_and_expressions
http://www.cprogramming.com/c++11/c++11-lambda-closures.html
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With