Object-Oriented Programming

Lambda Functions

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Function Pointer Usage

Problems

  • Have to create the function and name it
  • Naming things is good when we have a good name but a nuisance when we don't
  • Functions often cannot be defined in the program close to where they are used, so we have to search for it

Solution: Lambda Function

  • Also known as an anonymous function
  • C++11 feature
  • The simple form of a lambda function can be passed to a function pointer parameter
  • Lambda Function Syntax

Lambda Layout

  Term  
Capture Access to state from where the lambda is defined. We will leave it empty for now as this is a whole topic on its own, and only an empty capture can be used with function pointer parameters.
Parameters Pass state from the code that calls the lambda function
Return type Can be any function return type. Optional if void. In many cases, the compiler can derive the return type.
Body Definition of the lambda function. Where the statements go. Anything you can do in a free function you can do in a lambda function

Empty Lambda

  • Only isolated usage because there is no state for the function to work on

Lambda Parameter

  • Useful because the current state of the caller is passed to the callback
  • I.e., can compute based on the parameter

Lambda Parameters

lambda Description
IN parameter
IN/OUT parameter

Lambda: bool comparision

Lambda: int comparision

Call qsort() with lambda function

Call sort() with lambda function

Issues

  • The capture ([]) and captured variables are very important
  • Inline lambda functions create several formatting issues