ABSTRACT

In game programming, we often have the need to couple two or more completely unrelated classes at a higher level, making one of them call into the other. While engine and game systems should be isolated at a lower level as much as possible, sooner or later these systems have to talk to each other by some means. As an example, consider a character walking through a 3D environment. While the skeletal animation is driven by the animation system, playing footstep sounds would be the responsibility of the sound system, but neither of the systems in question should know about the existence of the other. In theory, this could be achieved by introducing interfaces as a bridge between unrelated classes. In practice, this is often frowned upon, because it creates coupling between the implementation and the corresponding interface and can have additional unwanted side effects. Furthermore, it leads to more boilerplate code being written and incurs extra function call overhead. In languages that treat functions as first-class citizens, this problem can be solved easily by passing around functions among all parties that somehow need to communicate. Since C++11, std::function offers such a general-purpose mechanism for passing around, storing, and invoking functions, supporting lambdas, member functions, and other function objects. While std::function is a welcome addition to the standard C++ library, this gem showcases a different solution to the underlying problem of tying unrelated types into a common interface. Most notably, this gem offers the following features, making it stand out from other implementations:

■ Lightweight. The size of a delegate is typically between 8 and 16 bytes, depending on the compiler and the platform. The size of a delegate is always constant for a given compiler and platform no matter what function it is bound to.