Saturday, January 20, 2007

The Policy Clone idiom

Modern C++ library design is heavily based on templates. Highly reusable, flexible and extensible classes can be built using policy based class design techniques. (See "Modern C++ Design" by Andrei Alexandrescu.) Sometimes, the host class of the policies need to make an exact replica of one of its policies but instantiated with different type parameter. Unfortunately, the writer of the host class template does not know the template name to instantiate beforehand. This situation is quite analogous to the situation in the Factory Method (GoF) pattern where type of the object to be created is not known apriori and therefore, the object creation is simply delegated to the derived object.

In the world of templates, although the problem is conceptually is quite similar, the mechanism to solve it is a different because we are interested in a "clone" type and not an object. The Policy Clone idiom comes handy here. A member template struct (called rebind) is used to pass a different type parameter to the policy class template. For example,

template <typename T>
class NiftyAlloc
template <typename Other>
struct rebind { /// The Policy Clone idiom
typedef NiftyAlloc<Other> other;

template <typename T, class Alloc = AllocationPolicy<T> >
class Vector {
typedef typename Alloc::template rebind<long>::other ClonePolicy;

Here, the Container template needs a replica of the allocation policy it is instantiated with. Therefore, it uses the rebind mechanism exposed by the NiftyAlloc policy. The type Alloc::template rebind<long>::other is same as NiftyAlloc<long>. Essentially, it says, "I don't know what kind of allocator this type is, and I don't know what it allocates, but I want an allocator just like it that allocates longs." To keep the compiler happy, we have to use both the keywords typename and template in the ClonePolicy typedef

The rule is as follows: If the name of a member template specialization appears after a ., ->, or :: operator, and that name has explicitly qualified template parameters, prefix the member template name with the keyword template. The Keyword typename is also necessary in the typedef because "other" is a type, not an variable. Hence the keywords!

As some of you out there might have guessed, this mechanism is used in standard STL containers and the Allocators used with them.

No comments: