Callback
- A callback is a bit of computation that a function/method can call when appropriate in the implemented algorithm
- They permit customization of the computation in a function/method
- Not a new programming mechanism
Common Control Flow
Callback Control Flow
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
- Each call to traverse can take a different callback
- 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
- Only the parameters are available to the callback
- Very useful when processing is quite complex, and it may be inefficient to save state and return each step
- The implementation of
Directory::process()
would probably not use an iterator but functions/methods native to the problem
- 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