Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 663

19


LISTING19.1 A Template of an ArrayClass


0: //Listing 19.1 A template of an array class
1: #include <iostream>
2: using namespace std;
3: const int DefaultSize = 10;
4:
5: template <class T> // declare the template and the parameter
6: class Array // the class being parameterized
7: {
8: public:
9: // constructors
10: Array(int itsSize = DefaultSize);
11: Array(const Array &rhs);
12: ~Array() { delete [] pType; }
13:
14: // operators
15: Array& operator=(const Array&);
16: T& operator[](int offSet) { return pType[offSet]; }
17:
18: // accessors
19: int getSize() { return itsSize; }
20:
21: private:
22: T *pType;
23: int itsSize;
24: };

There is no output, because this is not a complete program. Rather, this is the definition
of a scaled-down template.
The declaration of the template begins on line 5 with the keyword templatefol-
lowed by the parameter. In this case, the parameter is identified to be a type by
the keyword class, and the identifier Tis used to represent the parameterized type. As
mentioned earlier, you could also have used the word typenameinstead of class:
5: template <typename T> // declare the template and the parameter
You should use whichever word is clearer for you, although, it is recommended to use
classwhen the type is a class and typenamewhen it is not a class.
From line 6 until the end of the template on line 24, the rest of the declaration is like any
other class declaration. The only difference is that wherever the type of the object would
normally appear, the identifier Tis used instead. For example,operator[]would be
expected to return a reference to an object in the array, and, in fact, it is declared to
return a reference to a T.

ANALYSIS
Free download pdf