Quick Introduction to Lambda Functions
Adding lambda functions to C++ would let a programmer write a loop body in-place instead of having to write a separate STL-style function object. Similar capability is found in the anonymous method in C#, in the inner class in Java, and in the primordial lambda expression of LISP.
For example, currently a programmer who wants to convert a sequential for loop into a parallel_for has to write something like this:
// Without lambda expression
class ApplyFoo {
public:
int my_x;
ApplyFoo( int x ) : my_x(x) {}
void operator()(const blocked_range<size_t>& r) const {
for(size_t i=r.begin(); i!=r.end(); ++i)
Foo(i,my_x);
}
};
void ParallelApplyFoo(size_t n, int x) {
parallel_for(blocked_range<size_t>(0,n,10),
ApplyFoo(x));
}In particular, the programmer has to deal with capturing the value of parameter x in ParallelApplyFoo so that it can be referenced from ApplyFoo. The addition of lambda expressions, as recently proposed to the C++ Standards Committee, would enable the preceding example to be written more concisely as:
// With lambda expression
void ParallelApplyFoo(size_t n, int x) {
parallel_for(
blocked_range<size_t>(0,n,10),
<>const blocked_range<size_t>& r) {
for(size_t i=r.begin(); i<r.end(); ++i)
Foo(i,x);
});
}The <> directs the compiler to convert the expression after it into a function object that does everything the handcoded ApplyFoo would do. In general, lambda expressions let programmers pass blocks of code as parameters without having ...