Object-Oriented Programming

Callbacks: Lambda Functions

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Extremely Limited Binary Search

Better Binary Search

Function Generalization

  • Generalize a value
  • Generalize a range
  • Want to do this whenever it makes sense
  • But this is not enough

Sort

Generalization Problem

  • Comparison is fixed to <
  • For certain would want:
    • Ascending A..Z
    • Descending Z..A
  • But might want custom sort
  • Related issue: Generalizing the container and element types to sort (later)

Function Pointer

  • Take operation and make into a call to a comparison function
  • Pass comparison function as parameter
  • Parameter is a function pointer

Example: qsort()

  • C-library general QuickSort
  • man qsort
  • Messy to use
  • Will ignore how container is passed

qsort() Comparison Function

Using qsort()

Function Pointer

  • Can pass existing function by name
  • This is not a call
  • Call is made in the code when we reach that point. May be called multiple times.

Much Better Sort

Issue

  • 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 go look for it. E.g., convert.cpp

Solution: Use 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: []()->void {}

  • [] Capture. Will leave it empty for now. This is a whole topic on its own.
  • () Parameters. Passed by the code that calls the lambda function
  • -> void Return type
    • Optional if void
    • Can be any function return type
    • In many cases the compiler can derive the return type (differs between C++11, C++14, C++17)
  • {} 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

Process

  • Your function runs
  • When needed, calls function pointer
  • Finishes up and returns

Lambda Forms

  • []() {}
  • Only isolated usage because no state for the function to work on
  • [](int n){}
  • Useful because current state is passed to the callback
  • I.e., can compute based on the parameter

lambda: IN parameter

lambda: 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 is very important
  • Formatting inline lambda functions brings up issues