C++: Closures/Value Capture

Bjarne-stroustrup
 

Task: Create a list of 10 functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.

Goal: To demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

#include <iostream>
#include <functional>
#include <vector>

int main() {
	std::vector<std::function<int()> > funcs;
	for (int i = 0; i < 10; i++)
	funcs.push_back([=]() { return i * i; });
	for ( std::function<int( )> f : funcs ) 
	std::cout << f( ) << std::endl ; 
	return 0;
}
Output:
0
1
4
9
16
25
36
49
64
81

SOURCE

Content is available under GNU Free Documentation License 1.2.