More C++ Idioms/Thin Template

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

Thin Template
[edit | edit source]

Intent[edit | edit source]

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

Also Known As[edit | edit source]

Motivation[edit | edit source]

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. The greater the number of parameterized types, the larger 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 | edit source]

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 static_cast<T*>(VectorBase::at (index));
  }
};

The base class may be fat: it may contain an arbitrary amount of code. Because the base class uses only non-inline functions, its code is only generated once. But because the casting is encapsulated in the inline functions in the class template, the class is typesafe to its users. The templated class is thin, because it does not generate much code per template instantiation.

Known Uses[edit | edit source]

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 | edit source]

References[edit | edit source]

Symbian Essential Idioms: Thin Templates