Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
C++RAD Studio

Learn How To Use C++ Lambda Expressions In C++17 With C++Builder

lambda expressions

C++ got lots of additions throughout C++11, C++14 and C++17. Currently, C++ is a completely different language than it use to be. This Modern C++ post explains how to use the Standard Template Library and the most important features of the C++17 that will greatly help you write readable, maintainable, and expressive code!

One of the new features of C++11 was lambda expressions. Throughout C++11, C++14, and C++17, the lambda expressions got some new additions that made lambda expression even more powerful. 

If you do not know what lambda expression is, here is the answer:

  • Lambda expressions or lambda functions construct closures. A closure is a very generic term for unnamed (temporary) objects that can be called like functions and can capture variables in scope.

Lambda expressions are a great way to help to make code generic and tidy. Lambda expressions can be used as parameters for real generic algorithms to specialize in what those achieve when processing specific user-defined types. 

With lambda expressions, we can encapsulate code to call it later, and that also might be somewhere else because we can copy them around. 

Or we can also encapsulate code to call it multiple times with different parameters.

Let’s have a real example:

Pay attention to this line:

This is easy to use, just like any other binary function. As we defined its parameters to be of the auto type, it will work with anything that defines the plus operator (+), just as strings do.

And here we are using the lambda expression and printing the output to the console:

We do not need to store a lambda expression in a variable to utilize it. We can also define it in place and then write the parameters in parentheses just behind it (2, 2):

embarcadero c 17 lambda expressions 2394535

As you can see this is the syntax for lambda expressions. The shortest lambda expression possible is []{}, it just accepts no parameters, captures nothing, and essentially does nothing.

If you would like to explore more and want to learn what does rest mean be sure to check out these references!

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

About author

Software Developer | CS(CyberSec) Undergrad at APU Malaysia | Delphi/C++ Builder Enthusiast | Microsoft Learn Student Ambassador | Microsoft Azure Certified

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.