Jump to content

More C++ Idioms/Thin Template: Difference between revisions

From Wikibooks, open books for an open world
[unreviewed revision][unreviewed revision]
Content deleted Content added
→‎Motivation: Corrected an error (see discussion)
link to Symbian Essential Idioms: Thin Templates
Line 52: Line 52:


=== References ===
=== References ===

[http://developer.symbian.org/main/documentation/reference/s^3/doc_source/guide/EssentialIdioms/ThinTemplates.guide.html Symbian Essential Idioms: Thin Templates]


<noinclude>
<noinclude>

Revision as of 21:02, 18 March 2010

Thin Template

Intent

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

Also Known As

Motivation

Templates is 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

Thin template idiom is used 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 no) object code duplication.

// Not a template
class VectorBase {
  void insert (void *); 
  void *at (int index);
};

template <class T>
class Vector<T*> // Thin template 
   : 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

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