Common Control Flow

Callback

- A callback is a bit of computation from the caller that the called function or callee function can use whenever they need to in the implemented algorithm
- Callbacks permit customization of the computation in a function/method without changing the code in the computation
- Not a new programming mechanism
Control Flow Comparison


Callback Arguments
- free functions, function pointers
- lambda functions, anonymous functions
- functors, class that acts like a function
- methods, pointers to member functions
Example: Directory Traversal Iterator

Example: Directory Traversal Iterator

- Assume that
Directory
provides an iterator similar to std::vector
- The client has to know how to use the iterator
- Client calls
Directory
methods
Directory
methods do not call the client
- Have to know the methods available from the
Directory
Example: Directory Traversal Callback

Example: Directory Traversal Callback

- Only one call to traverse the directory
- Client calls
traverse()
- The method
traverse()
calls the client's output()
- The callback is provided the filename via a parameter that the
traverse()
calls each pass
- The whole process repeats until the directory is completely traversed
Example: Directory Traversal Callback

- Only the parameters, e.g.,
value
, are available to the callback
- Each call to
traverse()
can use a different callback
- Very useful when processing is quite complex, and it may be inefficient to save state and return each step
- The name of the callback,
process()
, is typically general as we don't know what it will be used for
- Processing of a directory is much more complex than this
Example: Process File


Callbacks

- Can be used with any level of complex processing
- Details of processing hidden inside the callback-enabled processor
- Client only has to provide the code to run when a particular event occurs
- Essential for asynchronous processing