{{announcement.body}}
{{announcement.title}}

All About Lambda Functions in C++ (From C++11 to C++17)

DZone 's Guide to

All About Lambda Functions in C++ (From C++11 to C++17)

· Web Dev Zone ·
Free Resource

Lambda functions are quite an intuitive concept of Modern C++ introduced in C++11, so there are already tons of articles on lambda function tutorials over the internet. But still, there are some untold things (like IIFE, types of lambda, etc.) left, which nobody talks about. Therefore, here I am to not only show you lambda function in C++, but we'll also cover how it works internally and other aspects of Lambda.

The title of this article is a bit misleading. Because lambda doesn't always synthesize to function pointer. It's an expression (precisely unique closure). But I have kept it that way for simplicity. So from now on, I will use lambda function and expression interchangeably.

What Is a Lambda Function?

A lambda function is a short snippet of code that:

  • Isn't worth naming (unnamed, anonymous, disposable, etc. Whatever you can call it),
  • and also will not be reused. 

In other words, it's just syntactic sugar. lambda function syntax is defined as: 

C++


Usually, the compiler evaluates a return type of a lambda function itself. So we don't need to specify a trailing return type explicitly i.e.  -> return-type

But, in some complex cases, the compiler unable to deduce the return type and we need to specify that.

Why Use a Lambda Function?

C++ includes many useful generic functions, like std::for_each, which can be handy. Unfortunately, they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. Consider the following code for an example: 

C++


If you use print once, in that specific place, it seems overkill to be writing a whole class just to do something trivial and one-off. 

However, this kind of situation inline code would be more suitable and appropriate which can be achieved by lambda function as follows: 

C++


How Lambda Functions Work Internally?  

C++


The compiler generates unique closure as above for each lambda function. Finally, the secret's revealed. Capture list will become a constructor argument in the closure. If you capture argument as a value, then the corresponding type data member is created within the closure.

Moreover, you can declare a variable/object in the lambda function argument, which will become an argument to call the operator i.e. operator().

Benefits of Using a Lambda Function

Zero cost abstraction. Yes! You read it right. Lambda doesn't cost you performance, and it's as fast as a normal function

In addition, code becomes compact, structured, and expressive.

Learning Lambda Expressions

Capture by Reference/Value

C++


Output:

C++


In the above example, I have mentioned & in the capture list. This captures variable x and y as a reference. Similarly, = denotes captured by value, which will create data member of the same type within the closure and copy assignment will take place. 

Note that the parameter list is optional; you can omit the empty parentheses if you do not pass arguments to the lambda expression.  

Lambda Capture List 

The following table shows different use cases for the same: 

[ ] ( ) { } no captures
[=] ( ) { } captures everything by copy(not recommendded)
[&] ( ) { } captures everything by reference(not recommendded)
[x] ( ) { } captures x by copy
[&x] ( ) { } captures x by reference
[&, x] ( ) { } captures x by copy, everything else by reference
[=, &x] ( ) { } captures x by reference, everything else by copy

Passing Lambda as a Parameter

C++


Output:

C++


You can also pass lambda functions as an argument to other functions just like a normal function, which I have coded above.

If you noticed, here I have declared a variable i in the capture list, which will become a data member. As a result, every time you call lambda_func, it will be returned and incremented.  

Capture Member Variable in Lambda or This Pointer 

C++


this pointer can also be captured using [this], [=] or [&]. In any of these cases, class data members(including private) can be accessed as you do in a normal method. 

If you see the lambda expression line, I have used extra () at the end of the lambda function declaration which used to calls it right thereafter declaration. It is called  IIFE (Immediately Invoked Function Expression).

C++ Lambda Function Types

Generic Lambda

C++


Generic lambda introduced in C++14 captures parameters with theauto specifier. 

Variadic Generic Lambda 

C++


Lambda with a variable parameter pack will be useful in many scenarios like debugging, repeated operation with different data input, etc.

Mutable Lambda Function

Typically, a lambda's function call operator is const-by-value, which means lambda requires the mutable  keyword if you are capturing anything by-value.

C++


We have already seen an example of this above.  I hope you noticed it.

Lambda as a Function Pointer 

C++


You can force the compiler to generate lambda as a function pointer rather than closure by adding + in front of it, as shown above. 

Higher-Order Returning Lambda Functions 

C++


Going a bit further, lambda functions can also return another lambda function. This will open the doors of endless possibilities for customization, code expressiveness, and compactibility (by the way, there is no word like this) of code.

Constexpr Lambda Expression

Since C++17, a lambda expression can be declared as constexpr.

C++


Even if you don't specify constexpr , the function call operator will be  constexpr anyway, if it happens to satisfy all constexpr function requirements.

Closing Words

I hope you enjoyed this article. I have tried to cover most of the intricacies around lambda with a couple of simple and small examples. You should use lambda wherever it strikes in your mind considering code expressiveness and easy maintainability like you can use it in custom deleters for smart pointers and with most of the STL algorithms.

Topics:
c++, c++ 11, lambda function, programming

Published at DZone with permission of Vishal Chovatiya . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}