Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Lambda Functions Are Ready for Prime Time-2 : Page 2


Due Closure

Using the new lambda syntax, you would rewrite the above find_if call like this:

double min_salary = 1000; double upper_lmt = 1.5*min_salary; std::find if(emps.begin(), emps.end(), [&](const employee& emp) (emp.salary() >= min_salary && emp.salary()< upper_lmt));

The last two lines contain a lambda expression which you'll explore in detail in a moment. Note that the manually defined function class is gone. Instead, the compiler implicitly generates a similar function class and replaces the user-written lambda expression with an unnamed function object of the generated class. The implicitly instantiated function object is called a closure.

Introducing Lambda

Let's look at the lambda expression itself. All lambda expressions begin with the lambda introducer [] (I'll explain the meaning of the & between the brackets later). The lambda's parameter list appears after the introducer. As with regular functions, the parameters are enclosed within parentheses. Finally, the last line contains the lambda expression's body:

(emp.salary() >= min_salary && emp.salary()< upper_lmt)

Here, the body contains only one statement. Because that evaluates to a Boolean expression, the compiler automatically deduces the lambda's return type as bool; however, you may declare the return type explicitly if you like, as shown below:

[&](const employee& emp)->bool //explicit return type (emp.salary() >= min_salary && emp.salary()< upper_lmt));

When the body of a lambda expression contains multiple statements, you have to enclose the body in braces and add an explicit return type:

//lambda body with multiple statements [](int x, int y)->int { int z; z = x + (y*2); return z; }

Let's analyze the last example:
  • [] is the introducer.
  • The parameter list declares x and y as int.
  • The explicit return type int is specified next.
  • Finally, the body, which contains three statements, is enclosed in braces.
Notice that the return keyword is mandatory when the body consists of multiple statements.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.