Chapter 5. Generalized Functors
This chapter describes generalized functors, a powerful abstraction that allows decoupled interobject communication. Generalized functors are especially useful in designs that need requests to be stored in objects. The design pattern that describes encapsulated requests, and that generalized functors follow, is Command (Gamma et al. 1995).
In brief, a generalized functor is any processing invocation that C++ allows, encapsulated as a typesafe first-class object. In a more detailed definition, a generalized functor
Encapsulates any processing invocation because it accepts pointers to simple functions, pointers to member functions, functors, and even other generalized functors—together with some or all of their respective arguments.
Is typesafe because it never matches the wrong argument types to the wrong functions.
Is an object with value semantics because it fully supports copying, assignment, and pass by value. A generalized functor can be copied freely and does not expose virtual member functions.
Generalized functors allow you to store processing requests as values, pass them as parameters, and invoke them apart from the point of their creation. They are a much-modernized version of pointers to functions. The essential differences between pointers to functions and generalized functors are that the latter can store state and invoke member functions.
After reading this chapter, you will
Understand the Command design pattern and how generalized functors relate to it
Know when the Command pattern and generalized functors are useful
Grasp the mechanics of various functional entities in C++ and how to encapsulate them under a uniform interface
Know how to store a processing request and some or all of its parameters in an object, pass it around, and invoke it freely
Know how to chain multiple such delayed calls and have them performed in sequence
Know how to use the powerful Functor class template that implements the described functionality
|