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 close to where they are used, so we have to search for it

Solution: Lambda Function

  • Also known as an anonymous function
  • Originated from Church's lambda calculus (λ-calculus)
  • C++11 feature
  • The simple form of a lambda function can be passed to a function pointer parameter
  • Lambda Function Syntax

Lambda Parts

Code Term Description
Lambda  
Capture Access to state from where the lambda is defined. We will leave it empty for now as this is a whole topic, 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
  • Can be used for tracing or debugging

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

Comparison

Aspect Function Pointer Lambda Function
Definition The function must be defined before it can be passed to a pointer Defined inline where it's used, with its body enclosed in {} and parameters in ()
Scope Global or namespace scope for the function being pointed to Scope is limited to where the lambda is defined
Capturing External Variables Not directly possible. External variables must be passed as parameters Can capture external variables from the surrounding scope either by value or by reference [&]
Portability Highly portable and compatible with C interfaces C++11
Performance Slightly slower than a direct call Provides more potential for compiler optimization

Issues

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