2.2 Parametrize the payload type

Listing 2 is the second trial. This time, we use a class template to parametrize the type of the payload of a list node.


Listing 2:Templateclasslinkedlist
 
1template <class T> class LinkedList 
2    T payload; 
3    LinkedList<T> *pNext; 
4  public
5    LinkedList<T>(void{ pNext = NULL; } 
6    LinkedList<T>(const T &v):payload(v) { pNext = NULL; } 
7    void setValue(const T &v) { payload = v; } 
8    T getValue(voidconst { return payload; } 
9    void setNext(LinkedList<T> *pNode) { pNext = pNode; } 
10    LinkedList<T> *getNext(void{ return pNext; } 
11};

Here, we use T as a “parameter” so that we can create different template classes by using a different actual type for T. For example, to specify a linked list of characters, we can use LinkedList<char>, and to specify a linked list of long integers, we can use LinkedList<long int>.

Note that T is not limited only to built-in types. If we have a class called Fraction, we can have a linked list of fractions as LinkedList<Fraction>.