Template Classes
Definition
- A class template is used by the compiler to generate the code for a class.
- You determine the class that you want generated by specifying your choice of type for the parameter that appears between the angled brackets in the template. Doing this generates a particular class called the **instance"" of the class template.
Implementing a class template
A class template is like a regular class definition, except it is prefixed by the keyword template.
Example 1: Class template for a stack.
template <class T> class Stack { public: Stack(int = 10) ; ~Stack() { delete [] stackPtr ; } int push(const T&); int pop(T&) ; int isEmpty()const { return top == -1 ; } int isFull() const { return top == size - 1 ; } private: int size ; // number of elements on Stack. int top ; T* stackPtr ; } ;
Example 2
#include <iostream> using std::cout; using std::endl; template <class T> // to indicate that you are defining a template rather than a class class Samples { public: Samples(const T values[], int count); Samples(const T& value); Samples() {m_Free = 0;} bool add(const T& value); // insert a value T max() const; // calculate maximum private: T m_Values[100]; // array to store samples int m_Free; // index of free location in m_Values }; template<class T> Samples<T>::Samples(const T& value) { m_Values[0] = value; m_Free = 1; //next is free } template<class T> Samples<T>::Samples(const T values[], int count) { m_Free = count < 100 ? count:100; // don't exceed the array for(int i = 0; i < m_Free; i++) m_Values[i] = values[i]; //store count number of samples } //function to add a sample template<class T> bool Samples<T>::add(const T& value) { bool OK = m_Free < 100; //indicates there is a free place if (OK) m_Values[m_Free++] = value; // ok true, so store the value return OK; } //function to obtain maximum sample template<class T> T Samples<T>::max() const { T theMax = m_Free ? m_Values[0] : 0; // set first sample or 0 as max for(int i = 1; i < m_Free; i++) if(m_Values[i] > theMax) theMax = m_Values[i]; return theMax; } int main() { double values[5] = {8.1, 1.3, 4.2, 3.4, 1.8}; Samples<double> myDoubles(values,5); cout << "The max is " << myDoubles.max() << endl; getchar(); }