Lambda Expressions are an expression that returns a function object, it comes with C++11 standards and used C++14, C++17, C++20 standards, it is well explained here. Lambda expressions are widely used in C++, C#, Groovy, Java, Python, Ruby languages too.
The Greek letter Lambda (λ) refers to an anonymous function, it means chosen since it is equated with something nameless and expression term means it is required since the code can be evaluated and will return a value.
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.
Simple Syntax of Lambda Expression is;
1 2 3 |
Datatype Lambda Expression = [Capture Clause] (Parameter List) -> Return Type { Body } |
Syntax of Lambda Expression (C++20) version is;
1 2 3 |
Datatype Lambda Expression = [Capture Clause] <Template Parameters> (Parameter List) Specifier Exception Attribute -> Return Type { Body } |
Here;
Datatype is its type like int, float, class, etc. and mostly auto term is used
Lambda Expression is a definition by the user
Capture Clause has variables that are visible in the body, capture can happen by value or reference and it can be empty
Parameter List can be empty or omitted
Return Type is a data type returned by the body, optional, normally deduced
Body contains the programming statements to execute and it can be empty
Now let’s see this syntax in an example. We will define a lambda expression to combine datatypes;
1 2 3 |
auto add_things = [](auto a, auto b) { return a + b; }; |
This can be used on any datatypes as given below;
1 2 3 4 5 6 7 8 9 10 11 12 |
auto add_things = [](auto a, auto b) { return a + b; }; // Lambda Expression auto i = add_things(1, 2); std::string hello = "hello"; std::string world = "world"; auto s = add_things(hello, world); std::cout << i << std::endl; std::cout << s << std::endl; |
In a modern way, 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;
1 2 3 4 5 6 7 8 9 10 11 12 |
auto add_things = [](auto a, auto b) { return a + b; }; // Lambda Expression auto i = add_things(1, 2); UnicodeString hello = L"hello"; UnicodeString world = L"world"; auto s = add_things(hello, world); Memo1->Lines->Add(i); Memo1->Lines->Add(s); |
Find out more about Lambda Expressions in the Embarcadero DocWiki.
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition