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-674287ddef7e0567498205/]

Pay attention to this line:

[crayon-674287ddef7e8675837874/]

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-674287ddef7e9380064665/]

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-674287ddef7ea710582459/]

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