Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have closures in C++?

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

like image 452
Parvinder Singh Avatar asked Sep 28 '12 07:09

Parvinder Singh


People also ask

Do closures exist 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.

What languages have closures?

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.

Are C++ lambdas closures?

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.

Does Python have closure?

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.


2 Answers

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

like image 127
Apeirogon Prime Avatar answered Sep 19 '22 15:09

Apeirogon Prime


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

like image 24
Zrin Avatar answered Sep 17 '22 15:09

Zrin