WEBINAR:
On-Demand
Application Security Testing: An Integral Part of DevOps
Presenting the Problem
The term a "lambda expression" originates of the mathematical field of
lambda calculus. To see what kind of problems a lambda expression can solve, consider the following invocation of the
transform() algorithm originally presented in a
previous 10-Minute Solution:
string s="hello";
transform(s.begin(), s.end(), s.begin(), toupper);
transform's fourth argument can be any callable entity, say a
functor, a
bound member function or a
freestanding function. Now, suppose you want to apply a different type of transformation to the stringnamely mask every character with an asterisk. You want to be able to write something like this:
transform(s.begin(),
s.end(),
s.begin(),
='*');
Of course, this code won't compile. Instead, you have to write a full-blown function first:
int toasterisk(int original_letter)
{
return '*';
}
And call transform() like this:
transform(s.begin(), s.end(), s.begin(), toasterisk);
Using
for_each() instead of
transform() for such a task seems more natural:
for_each(s.begin(), s.end(), toasterisk);
But still, the third argument must be the name of a function defined elsewhere in the program. This coding style, though inevitable, is artificial and unwieldy. In some cases, it also compromises encapsulation. Take a look at how to define an unnamed function on the call site using the
lambda library.