2.3.2 Class templates

Class templates to build containers. The motivation to create class templates is closely related to the use of containers. "However, container classes have the interesting property that the type of objects they contain is of little interest to the definer of a container class, but of crucial importance to the user of the particular container. Thus we want to have the type of the contained object be an argument to a container class: [...]", [1], §8. That means that a container - e.g. a vector - should be able to contain objects of any type. This is achieved by class templates. The following example comes from [1], §1.4.3:

template <class T>
class vector {
   T* v;
   int sz;
   vector (int s) { v = new T [sz = s]; }
  ~vector () { delete[] v; }
   T& operator[] (int i) { return v[i]; }
   int get_size() { return sz; }

Note that no error-checking is done in this example. You can instantiate different vector-containers which store objects of different types:

vector<int>	int_vector (10);
vector<char>	char_vector (10);
vector<shape>	shape_vector (10);

Take a look at the notation, the type-name is vector<specific_type>.

Continue with section 2.3.3

Back to index

Johannes Weidl (J.Weidl@infosys.tuwien.ac.at) - Apr 16, 1996