Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

The Advanced Guide To Lambda Expression In C++ Software

lambdaexpression

What is a Lambda Expression?

A Lambda Expression defines an anonymous function or a closure at the point where it is used. You can think of a lambda expression as an unnamed function (that’s why it’s called “anonymous”). Lambda expressions help make your C++ software code cleaner, more concise, and allow you to see behavior inline where it’s defined instead of referring to an external method, like a function.

Lambda Expressions are an expression that returns a function object. Lambda expressions are widely used in C++ as well as the C#, Groovy, Java, Python, Ruby languages too.

Where does the name Lambda Expression come from?

The Greek letter Lambda ( λ ) refers to an anonymous function – a function without a name so we use the word “lambda” instead.

A Lambda Expression is assignable to a variable whose data type is usually auto and defines a function object.

Syntax for a lambda expression consists of specific punctuation with = [ ] ( ) { … } series. 

Lambda expressions are one example of modern C++ language features. The aim of this article is to provide information about lambda expressions, parts of the expressions, and how they can be used while writing code.

What is the syntax of the Lambda Expression?

The syntax for a lambda expression consists of specific punctuation with = [ ] ( ) { ... } series. 

The basic syntax of a Lambda Expression is;

[crayon-6736bbe1761f4609787352/]

The basic syntax of Lambda Expression in C++20 version is;

[crayon-6736bbe1761fe665848203/]

Here;

Now lets see each of them.

What other parts of Lambda Expression syntax are there?

The Lambda Expression’s Datatype

Datatype is the data type of the lambda expression which is its type like int, float etc. In modern C++, mostly auto term is used.

Lambda Expression 

It is an expression, a definition by the user. It is used like a class name or method name.

Learn about lambda function C++, the parts of the expressions, and how this function can help you drastically improve how you write code.

The Lambda Expression’s capture clause

Capture clauses are used to instruct the compiler to capture the variables visible in scope around where the lambda is declared, either by copy or by reference, to be available for use inside the lambda method body. Capture clauses can be used in different ways to specify the requirements of functions.

The capture clause is the first part of a lambda, in square brackets [].

Here are a few ways to declare capture clauses:

  1. [ ] : Empty Capture. It means that nothing should be captured. Lambda Expression can be written as auto L= [ ] ( ) { };
  2. [ = ] : Capture Value in Definition. It specifies that all variables used in the function’s definition should be captured by value. It makes capture by value the default capture type. Lambda Expression can be written as auto L= [ = ] ( ) { };
  3. [ & ] : Capture Value in Usage. It specifies that all variables used in the function’s definition should be captured by reference. It makes capture by reference the default capture type. Lambda Expression can be written as auto L= [ & ] ( ) { };
  4. [*this] : Capturing *this was introduced in C++11. Its purpose is to either capture the copy of the current object, or capture the object itself. Capturing [*this] by value was introduced in C++17. Capturing [*this] by value is important in a scenario where a lambda expression is asynchronously dispatched from a non-static member function. The pointer might not be valid when the function runs. For that reason, it is important to be able to capture *this by value. You can read more about the new feature here: Lambda Capture of *this by Value as [=,*this]
  5. Multiple Capture. Both [=] and [&] can be used together in one capture clause. For example, [=, &var] specifies that all variables should be captured by copy but variable “var” should be captured by reference.
    Some capture clause definitions result in errors due to redundancy. For example, a capture clause like [&, &var] is problematic since we already specified that all variables should be captured by reference and then re-specified that var should be captured by reference.    
  6. Capture by Copy. Similarly, you can capture all variables by reference and specify particular variables to capture by copy. For example, [&, var] specifies that all variables should be captured by reference but variable “var” should be captured by copy.  

Lambda Expression parameters

The parameter list of a lambda is just like the parameter list of any other method: a set of parameters inside braces (). Input parameters in a lambda expression can be listed while defining lambda expressions but are not required.  

The Lambda Expression’s return Type

Often the return type does not need to be specified because it can be deduced by the compiler. If you have a single return statement, the compiler can easily deduce the return type. For more complex lambdas you may need or choose to specify it explicitly.

The Lambda Expression’s Body

The body of a lambda expression simply contains the code, the same as a normal function. It is defined between { and } characters.

Get information about C++ lambda expressions, parts of the expressions, and how they can be used while writing code.

What are the different ways of writing lambda expressions?

We have added a couple of snippets of lambda expressions using Embarcadero’s C++Builder.

1. [ Captures ] ( Params ) -> ReturnType { Body };

In this method, we are using a capture clause, specifying some parameters, as well as the return type.

Sample code:

[crayon-6736bbe176201304250617/]

What this code means is that all variables should be available copied by value and the return type of the function is int. The statements enclosed within the curly braces represent the body of the function: note that the method both uses a variable outside the lambda (value, captured by copy, so available as a const value) and a normal parameter (a)

For this lambda the compiler could deduce what the return type is, but we’ve specified it anyway as int.

2. [ Captures ] ( Params ) { Body };

In this method, we are using a capture clause, and specifying some parameters. The return type should be deduced.

Sample code:

[crayon-6736bbe176204997517881/]

What this means is that all variables should be available by reference (meaning they can be written back to) and the return type of the function should be deduced. The statements enclosed within the curly braces represent the body of the function.

Normally, captured variables are const value variables. They are copies and cannot be modified. Here, since value is captured by reference, you can modify the value of “value” from within the lambda.

3. [ Captures ] { Body }; 

In this method, we are using a capture clause, and have excluded parameters. The return type should be deduced.

Sample code:

[crayon-6736bbe176206255737491/]

Lambda expressions can also be written by only specifying the capture clause and defining the body of the function. When the return type is not specified, it will be deduced.

What changes to Lambda Expressions were made in C++17?

Updates to several features were made in C++17. Some of the changes made to lambda expressions in C++17 include:

In conclusion, lambda expressions provide a neat and concise alternative to writing functions. They can be declared in different ways based on users’ requirements by making use of capture clauses and parameters (which are optional). Additionally, return types can be deduced and lambda expressions can be declared as constexpr.

What are some examples of Lambda Expressions?

Now let’s see more syntax examples. We will define a lambda expression to combine datatypes;

[crayon-6736bbe176209625732315/]

This can be used on any datatypes as given below;

[crayon-6736bbe17620a392519556/]

In modern C++ software, we can use UnicodeString in C++ Builder VCL or FMX projects. This code will support worldwide languages. Here below we used the Memo component as an output;

[crayon-6736bbe17620c370881740/]

Is there a full example of C++ software Lambda Expression?

This is a full example about the lambda expression, it has 3 different ways of usage. It is also good to understand auto

[crayon-6736bbe17620e280893731/]

Lambda Expressions have some advantages and disadvantages, now lets see them.

What are the pros of using a C++ Lambda Expression?

Lambda expressions are lightweight, nameless functions that can be defined just-in-place where they are used. Lambdas expression feature is not a specific-purpose feature like functional programming etc. Lambda expressions allow you to specify function arguments as lambdas beside C-like functions and functors. Unless you need a function available in more than one place, you’ll feel more comfortable using lambdas as arguments of STL components. Because of their features, Lambda Expressions have some advantages;

What are the cons of using a Lambda Expression in C++ software?

Since the lambda expressions has been introduced in C++11 standards (2011) – as it that allow you to write an inline, anonymous functor to replace the struct f – still it is not popular in C++ usage among the developers. I try to list some of the reasons, and its disadvantages below,

Find out more about Lambda Expressions in the Embarcadero DocWiki.

C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.

There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.

Exit mobile version