Contents Up << >>

What's the syntax / semantics for a "class template"?

Consider a container class of that acts like an array of integers:

  	//this would go into a header file such as "Array.h"
	class Array {
	public:
	  Array(int len=10)                  : len_(len), data_(new int[len]){}
 	 ~Array()                            { delete [] data_; }
 	  int len() const                    { return len_;     }
 	  const int& operator[](int i) const { data_[check(i)]; }
 	        int& operator[](int i)       { data_[check(i)]; }
 	  Array(const Array&);
	  Array& operator= (const Array&);
	private:
	  int  len_;
	  int* data_;
	  int  check(int i) const
	    { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
	      return i; }
 	};
Just as with "swap()" above, repeating the above over and over for Array of float, of char, of String, of Array-of-String, etc, will become tedious.

  	//this would go into a header file such as "Array.h"
	template
	class Array {
	public:
	  Array(int len=10)                : len_(len), data_(new T[len]) { }
 	 ~Array()                          { delete [] data_; }
 	  int len() const                  { return len_;     }
 	  const T& operator[](int i) const { data_[check(i)]; }
 	        T& operator[](int i)       { data_[check(i)]; }
 	  Array(const Array&);
	  Array& operator= (const Array&);
	private:
	  int len_;
	  T*  data_;
	  int check(int i) const
	    { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_);
	      return i; }
 	};
Unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating:

  	main()
	{
	  Array           ai;
	  Array         af;
	  Array         ac;
	  Array        as;
	  Array< Array >  aai;
	}              // ^^^-- note the space; do {\it not} use "Array>"
	               //       (the compiler sees ">>" as a single token).