13 Dancing the lambda

 

This chapter covers

  • Understanding the concept of Lambdas
  • Learning how to capture values by value and reference using lambdas
  • Exploring how lambdas and the STL can co-work
  • Practicing how to pass lambda expressions to functions
  • Exploring the concept of dynamic programming and lambdas

Lambdas are powerful tools that can elevate your programming skills to new heights. In this chapter, we will explore the concept of lambdas, their syntax, and their incredible flexibility.

Lambdas allow us to create anonymous functions on the fly, providing a concise and expressive way to encapsulate behavior. They are particularly useful in situations where we need to pass functions as arguments, or create small, self-contained functions without the need for separate function definitions.

Throughout this chapter, we will unravel the mysteries of lambdas: You’ll learn how to create and use lambdas, understand their underlying mechanics, and explore their versatility in various scenarios, such as capturing variables by value and reference.

In this chapter, you will also learn about generic lambdas and their flexibility in working with different argument types. Furthermore, we explore how lambdas integrate well with algorithms and can be used as callbacks or return values with the help of std::function.

13.1 Lambda expression: The powerful one-liner

13.1.1 Sing the la-la-la-lambda: Lambdas at work

13.1.2 Capturing variables by value and by reference

13.1.3 When C++23 plays a-tribute: The new lambda attributes

13.1.4 Lambdas and STL algorithms – The Ying and Yang of C++

13.1.5 The typist: Lambdas, templates and typename

13.1.6 Passing lambda expressions as function arguments

13.1.7 The love child of lambdas and concepts: The lambda’s requires clause

13.1.8 Constexpr and lambda

13.1.9 The recursive lambda dance - C++23 recursive lambdas

13.1.10 Lambda and dynamic programming: a short introduction

13.2 Coding exercise: Dancing the lambda – literally…

13.3 Summary