Creating Class Template Stack<T>

The Stack class-template definition in Fig. 18.1 looks like a conventional class definition, with a few key differences. First, it’s preceded by line 7

template< typename T >


 1   // Fig. 18.1: Stack.h
 2   // Stack class template.
 3   #ifndef STACK_H
 4   #define STACK_H
 5   #include <deque>
 6
 7   template< typename T >
 8   class Stack
 9   {
10   public:
11      // return the top element of the Stack
12      T& top()
13      {
14         return stack.front();
15      } // end function template top
16
17      // push an element onto the Stack
18      void push( const T &pushValue )
19      {
20         stack.push_front( pushValue );
21      } // end function template push
22
23      // pop an element from the stack
24      void pop()
25      {
26         stack.pop_front();
27      } // end function template pop
28
29      // determine whether Stack is empty
30      bool isEmpty() const
31      {
32         return stack.empty();
33      } // end function template isEmpty
34
35      // return size of Stack
36      size_t size() const
37      {
38         return stack.size();
39      } // end function template size
40
41   private:
42      std::deque< T > stack; // internal representation of the Stack
43   }; // end class template Stack
44
45   #endif


Fig. 18.1. Stack class template.

All class templates begin with keyword template followed by a list of template parameters enclosed in angle brackets (< and >); each template parameter that represents a type must be preceded by either of the interchangeable keywords typename or class. The type parameter T acts as a placeholder for the Stack’s element type. The names of type parameters must be unique inside a template definition. You need not specifically use identifier T—any valid identifier can be used. The element type is mentioned generically throughout the Stack class-template definition as T (lines 12, 18 and 42). The type parameter becomes associated with a specific type when you create an object using the class template—at that point, the compiler generates a copy of the class template in which all occurrences of the type parameter are replaced with the specified type. Another key difference is that we did not separate the class template’s interface from its implementation.


Image Software Engineering Observation 18.2

Templates are typically defined in headers, which are then #included in the appropriate client source-code files. For class templates, this means that the member functions are also defined in the header—typically inside the class definition’s body, as we do in Fig. 18.1.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.70.101