Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

More C++ Idioms/Parameterized Base Class

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Parameterized Base Class Intent To abstract out an aspect in a reusable module and combine it in a given type when required. Also Known As Mixin-from-below Parameterized Inheritance Motivation 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 template <class T> class Serializable : public T, /// Parameterized Base Class Idiom public ISerializable { public: 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 Related Idioms Curiously Recurring Template Pattern References ja:More C++ Idioms/パラメータ化された基本クラス(Parameterized Base Class)