C++ Notes: Templates

The Problem: To define containers for any class

It is relatively easy to define a class, like vector, that will work with one specific type. to use the class with another type, you must replace all type names in the original file with the new type, an error-prone process. C++ provides a way to write a generic definition that works with any type -- templates. Use templates only to define classes that you want to work with many data types.

Standard Template Library

Common containers (data structures) and algorithms have already been written and are available in what is usually called the Standard Template Library (STL). This library includes definitions for vector, set, multiset, map, multimap, queue, stack, and more.

Templates can be used with classes or functions

Precede the class or function with
   template <class sometype>

The header file (.h) includes all method definitions

Because the compiler needs to know which for types to compile the implementation of a template, it is necessary to include the implementations of all methods in the .h file. There will be no separate .cpp file for the template methods, constructors, and destructors, unlike the typical C++ pattern which requires the separation.

There are two styles for doing this:
  1. Putting the implementation directly in the class definition. Advantage: The header information doesn't have to be repeated twice. It's the way Java defines all classes. Disadvantage: It's harder to read a short summary of the class. Template Example 1 uses this style.
  2. Making a class definition with only prototypes and immediately following it with the definitions. Advantage: the class definition is short and easily readable. Disadvantage: the header information is in two places.

Related Pages