Policy-based design was first introduced by Andrei Alexandrescu in his excellent Modern C++ Design book. Although published in 2001, many ideas showed in it are still used today. We recommend reading it; you can find it linked in the Further reading section at the end of this chapter. The policy idiom is basically a compile-time equivalent of the Gang of Four's Strategy pattern. If you need to write a class with customizable behavior, you can make it a template with the appropriate policies as template parameters. A real-world example of this could be standard allocators, passed as a policy to many C++ containers as the last template parameter.
Let's return to our Array class and add a policy for debug printing:
template <typename T, typename DebugPrintingPolicy = NullPrintingPolicy> class Array {
As you can see, we can use a default policy that won't print anything. NullPrintingPolicy can be implemented as follows:
struct NullPrintingPolicy...