< More C++ Idioms

Thin Template

Intent

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

Also Known As

Motivation

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

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, it's 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

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

template <class T> class CArrayFix : public CArrayFixBase

where CArrayFixBase does all the work

References

Symbian Essential Idioms: Thin Templates

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.