Class Templates

Templates can be provided for classes as well as functions. This is how we create generic classes that work with any data type (predefined or programmer-defined). This concept is also the basis (in C++) for container classes -- classes that hold collections of objects. These are the data structures studied in CMSC 341.

SmartArray revisited

The SmartArray class we designed earlier in the semester contain a dynamically allocated array of integers. class SmartArray { public: SmartArray (int size = 100); // other members private: int m_size; int *m_theData; // this is what makes it a SmartArray of ints }; Nothing in the algorithms for the SmartArray code relies on the fact that this is an array of integers. For example // SmartArray constructor SmartArray::SmartArray (int size) : m_size( size ) { m_data = new int [ m_size ]; } // SmartArray destructor SmartArray::~SmartArray( void ) { delete [ ] m_data; m_data = 0; } // Get a single element int SmartArray::at( int i ) const { return m_data[ i ]; }

We can create a class template for SmartArray so that we use it for any primitive data type or class (assuming that the class has the necessary overloaded operators).

Class template for SmartArray

As with function templates, we use a template parameter ( T ) to take the place of the generic data type. template <class T> class SmartArray { public: SmartArray ( int size = 100 ); // other members private: int m_size; T *m_theData; // array of any type };

Each of the SmartArray methods is a function template

// SmartArray constructor template <class T> SmartArray<T>::SmartArray (int size) : m_size( size ) { // an array of Ts using T's default constructor m_theData = new T [m_size]; } //----------------------------------- // copy constructor //----------------------------------- template <class T> SmartArray<T>::SmartArray (const SmartArray<T>& array) { m_size = array.m_size; m_theData = new T [ m_size ]; for (int j = 0; j < m_size; j++ ) m_theData[ j ] = array.m_theData [ j ]; } // Get a single element template <class T> const T& SmartArray<T>::at( int i ) const { return m_data[ i ]; }

Using the SmartArray class template

In the main program,

#include "SmartArray.H"

Define some SmartArrays:

SmartArray<float> array1; SmartArray<myClass> array2; When the compiler sees these definitions, it looks for the SmartArray class template to determine how to generate the needed class code. Note that it's not possible to create a SmartArray object without designating the real type that replaces 'T' in the template.

There's no such thing as a "SmartArray" object... only "SmartArray of int" objects and "SmartArray of float" objects and "SmartArray of Bob" objects.

Last Modified: Monday, 28-Aug-2006 10:16:05 EDT