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

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 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:

[crayon-676bcc8890415816718107/]

Pay attention to this line:

[crayon-676bcc889041e089570231/]

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:

[crayon-676bcc8890420895199354/]

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):

[crayon-676bcc8890421769868425/]

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!

Exit mobile version