More C++ Idioms/Thin Template

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

Thin Template[edit]

Intent[edit]

To reduce object code duplication when a class template is instantiated for many types.

Also Known As[edit]

Motivation[edit]

Templates are a way of reusing source code, not object code. A template can be defined for a whole family of classes. Each member of that family that is instantiated requires its own object code. Whenever a class or function template is instantiated, object code is generated specifically for that type. More the number of parameterized types, more is the generated object code. Compilers only generate object code for functions for class templates that are used in the program, but duplicate object code could still pose a problem in environments where memory is not really abundant. Reusing the same object code could also improve instruction cache performance and thereby application performance. Therefore, it is desirable to reduce duplicate object code.

Solution and Sample Code[edit]

Thin template idiom is used to reduce duplicate object code. Object code level reusable code is written only once, generally in a base class, and is compiled in a separately deployable .dll or .so file. This base class is not type safe but type safe "thin template" wrapper adds the missing type safety, without causing much (or any) object code duplication.

// Not a template
class VectorBase {
  void insert (void *); 
  void *at (int index);
};
 
template <class T>
class Vector<T*> // Thin template 
   : public VectorBase 
{
  inline void insert (T *t) {
     VectorBase::insert (t);
  }
  inline T *at (int index) {
     return VectorBase::at (index);
  }
};

The base class may be fat: it may contain an arbitrary amount of code. Because this class uses only inline functions, it generates no extra code. But because the casting is encapsulated in the inline function, the class is typesafe to its users. The templated class is thin

Known Uses[edit]

Symbian OS relies on this idiom a lot. For example,

template <class T> class CArrayFix : public CArrayFixBase

where CArrayFixBase does all the work

Related Idioms[edit]

References[edit]

Symbian Essential Idioms: Thin Templates