Lambda expressions
A lambda is essentially an anonymous function as a literal expression:
auto la = []{ return "Hello\n"; };
The variable la
may now be used as if it were a function:
cout << la();
It can be passed to another function:
f(la);
It can be passed to another lambda:
const auto la = []{ return "Hello\n"; }; const auto lb = [](auto a){ return a(); }; cout << lb(la);
Output:
Hello
Or it can be passed anonymously (as a literal):
const auto lb = [](auto a){ return a(); }; cout << lb([]{ return "Hello\n"; });
Closures
The term closure is often applied to any anonymous function. Strictly speaking, a closure is a function that allows the use of symbols outside its own lexical scope.
You may have noticed the square brackets in the definition of a lambda:
auto la = []{ return "Hello\n"; };
The square brackets are used to specify a list of captures. Captures are outside variables...