January 2019
Intermediate to advanced
512 pages
14h 5m
English
Class templates are classes that use generic types, usually to declare its data members, but also to declare methods and local variables inside them:
template <typename T>class ArrayOf2 { public: T& operator[](size_t i) { return a_[i]; } const T& operator[](size_t i) const { return a_[i]; } T sum() const { return a_[0] + a_[1]; } private: T a_[2];};
This class is implemented once, and can then be used to define an array of two elements of any type:
ArrayOf2<int> i;i[0] = 1; i[1] = 5;std::cout << i.sum(); // 6ArrayOf2<double> x;x[0] = -3.5; x[1] = 4;std::cout << x.sum(); // 0.5ArrayOf2<char*> c;char s[] = "Hello";c[0] = s; c[1] = s + 2;
Pay particular attention to the last example—you might expect the ArrayOf2 template not ...