Templates

    Reading: Dietel sections 12.1-12.5

Polymorphism

Motivation

Template Functions

Caution

 

 

Template Classes

Revisiting the SmartArray Class

template <class T>        // copy constructor
SmartArray <T> :: SmartArray (const SmartArray<T>& a)
{
  size = a.size;
  data = new T [ size ];
for (int j = 0; j < size; j++ )
data[ j ] = a.data [ j ];
}
template <class T>        // overloaded [ ]
T& SmartArray<T>::operator[ ] (int index)
{
return data [ index ] ;  // no error checking 
}
 

To declare some SmartArrays:

    SmartArray < int > ( 50 );
    SmartArray < Rational > ( 23 );

When this code is encountered, compiler must know the class template in order to instantiate the (int or Rational version of the) class and its member functions.

File Organization

Template Compilation