3.1 Class template declaration and definition

The declaration of a class template is what is needed for another source code to use the class template. It does not need to include the definitions of how methods are implemented. An example is illustrated in listing 3.


Listing 3:Classtemplatedeclaration
 
1// this should be in ll.h 
2#ifndef __LL_H 
3#define __LL_H 
4template <class T> class LinkedList 
5    T payload; 
6    LinkedList<T> *pNext; 
7  public
8    LinkedList<T>(void); 
9    LinkedList<T>(const T &v); 
10    void setValue(const T &v); 
11    T getValue(voidconst
12    void setNext(LinkedList<T> *pNode); 
13    LinkedList<T> *getNext(void); 
14}
15#endif

The class template declarations are typically stored in a header file to be included in client source code that need to use the class template.

The definition of a class template specifies how methods are implemented. An example is illustrated in listing 4.


Listing 4:Classtemplatedefinitions
 
1// this should be in ll.cc 
2#include ”ll.h” 
3#ifndef NULL 
4#define NULL 0 
5#endif 
6template <class T> LinkedList<T>::LinkedList(void{ pNext = NULL; } 
7template <class T> LinkedList<T>::LinkedList(const T &v):payload(v) { pNext = NULL; } 
8template <class T> void LinkedList<T>::setValue(const T &v) { payload = v; } 
9template <class T> T LinkedList<T>::getValue(voidconst { return payload; } 
10template <class T> void LinkedList<T>::setNext(LinkedList<T> *pNode) { pNext = pNode; } 
11template <class T> LinkedList<T> *LinkedList<T>::getNext(void{ return pNext; }

The class template definition is usually stored in a source file with an extension of .cc, .c++ or .C.