|
||||
Section 35:
|
[35.2] What's the syntax / semantics for a "class template"?
Consider a container class Array 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_; } int const& operator[](int i) const { return data_[check(i)]; } ← subscript operators often come in pairs int& operator[](int i) { return data_[check(i)]; } ← subscript operators often come in pairs Array(Array const&); Array& operator= (Array const&); private: int len_; int* data_; int check(int i) const { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_); return i; } };Repeating the above over and over for Array of float, of char, of std::string, of Array-of-std::string, etc, will become tedious. // This would go into a header file such as "Array.h" template<typename T> class Array { public: Array(int len=10) : len_(len), data_(new T[len]) { } ~Array() { delete[] data_; } int len() const { return len_; } T const& operator[](int i) const { return data_[check(i)]; } T& operator[](int i) { return data_[check(i)]; } Array(const Array<T>&); Array<T>& operator= (const Array<T>&); private: int len_; T* data_; int check(int i) const { if (i < 0 || i >= len_) throw BoundsViol("Array", i, len_); return i; } };Just as with a normal class, you can optionally define your methods outside the class: template<typename T> class Array { public: int len() const; ... }; template<typename T> inline ← see below if you want to make this non-inline int Array<T>::len() const { ... }Unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating: int main() { Array<int> ai; Array<float> af; Array<char*> ac; Array<std::string> as; Array< Array<int> > aai; ... }Note the space between the two >'s in the last example. Without this space, the compiler would see a >> (right-shift) token instead of two >'s. |