More C++ Idioms/Parameterized Base Class

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Parameterized Base Class
[edit | edit source]

Intent[edit | edit source]

To abstract out an aspect in a reusable module and combine it in a given type when required.

Also Known As[edit | edit source]

  • Mixin-from-below
  • Parameterized Inheritance

Motivation[edit | edit source]

A certain aspect can be abstracted out from requirements and be developed as templates (e.g., object serialization). Serialization is a cross-cutting concern that many classes/POD types in an application may have. Such a concern can be abstracted out in a manageable reusable module. By addition of an aspect, substitutability with the original type is not broken so another motivation is to have a IS-A (public inheritance) or WAS-A (private inheritance) relationship with the type parameter.

Solution and Sample Code[edit | edit source]

template <class T>
class Serializable : public T,   /// Parameterized Base Class Idiom
                     public ISerializable
    Serializable (const T &t = T()) : T(t) {}
    virtual int serialize (char *& buffer, size_t & buf_size) const
        const size_t size = sizeof (T);
        if (size > buf_size)
          throw std::runtime_error("Insufficient memory!");

        memcpy (buffer, static_cast<const T *>(this), size);
        buffer += size;
        buf_size -= size;
        return size;

Serializable <T> can be used polymorphically as a T as well as a ISerializable. Above example works correctly only if T is a user-defined POD type without pointers.

Known Uses[edit | edit source]

Related Idioms[edit | edit source]

References[edit | edit source]