Loading lessons...
Generic Classes: Class Templates
Generic Classes: Class Templates
A stack of ints and a stack of doubles need exactly the same code; only the element type differs. A class template (a generic class) describes a whole family of classes with the type as a parameter.
Stack<int> and Stack<double> are then generated by the compiler. Every STL container (vector<T>, list<T>, map<K, V>) is a class template.
1. Syntax
An object is created by giving the actual type in angle brackets. The type cannot be deduced, so it must always be written:
The process of creating a specific class from the template is called instantiation; Stack<int> is a template class (an instance of the class template Stack).
2. A Generic Stack
#include <iostream>
using namespace std;
template <class T>
class Stack {
enum {
MAX = 5
};
T items[MAX];
int top;
public:
Stack() {
top = -1;
}
bool isEmpty() const {
return top == -1;
}
bool isFull() const {
return top == MAX - 1;
}
void push(const T& x) {
if (isFull()) {
cout << "Stack full, cannot push " << x << endl;
} else {
items[++top] = x;
}
}
T pop() {
return items[top--];
}
};
int main() {
Stack<int> si; // T = int
Stack<double> sd; // T = double
Stack<char> sc; // T = char
for (int i = 1; i <= 3; i++) {
si.push(i * 100);
}
sd.push(1.5);
sd.push(2.75);
const char* word = "OOP";
for (int i = 0; word[i] != '\0'; i++) {
sc.push(word[i]);
}
cout << "int stack: ";
while (!si.isEmpty()) {
cout << si.pop() << " ";
}
cout << endl << "double stack: ";
while (!sd.isEmpty()) {
cout << sd.pop() << " ";
}
cout << endl << "char stack: ";
while (!sc.isEmpty()) {
cout << sc.pop();
}
cout << endl;
return 0;
}Output:
int stack: 300 200 100
double stack: 2.75 1.5
char stack: POO3. Member Functions Defined Outside the Class
A member function of a class template defined outside the class is itself a template. It needs the template header again, and the class name is written with its parameter: ClassName<T>::.
#include <iostream>
using namespace std;
template <class T>
class Vector {
T* v;
int size;
public:
Vector(int n);
Vector(const T* a, int n);
~Vector() {
delete[] v;
}
T operator*(const Vector& y) const; // dot product
void show() const;
private:
Vector(const Vector&); // copying not needed in this example
Vector& operator=(const Vector&);
};
template <class T>
Vector<T>::Vector(int n) {
size = n;
v = new T[size];
for (int i = 0; i < size; i++) {
v[i] = 0;
}
}
template <class T>
Vector<T>::Vector(const T* a, int n) {
size = n;
v = new T[size];
for (int i = 0; i < size; i++) {
v[i] = a[i];
}
}
template <class T>
T Vector<T>::operator*(const Vector& y) const {
T sum = 0;
for (int i = 0; i < size; i++) {
sum = sum + v[i] * y.v[i];
}
return sum;
}
template <class T>
void Vector<T>::show() const {
cout << "(";
for (int i = 0; i < size; i++) {
cout << v[i] << (i < size - 1 ? ", " : ")");
}
cout << endl;
}
int main() {
int x[3] = {1, 2, 3}, y[3] = {4, 5, 6};
Vector<int> v1(x, 3), v2(y, 3);
v1.show();
v2.show();
cout << "v1 . v2 = " << v1 * v2 << endl; // 4 + 10 + 18
double p[2] = {1.5, 2.0}, q[2] = {2.0, 0.25};
Vector<double> d1(p, 2), d2(q, 2);
cout << "d1 . d2 = " << d1 * d2 << endl; // 3 + 0.5
return 0;
}Output:
(1, 2, 3)
(4, 5, 6)
v1 . v2 = 32
d1 . d2 = 3.54. Class Templates with Multiple Parameters
A class template can have several type parameters, separated by commas.
#include <iostream>
using namespace std;
template <class T1, class T2>
class Pair {
T1 first;
T2 second;
public:
Pair(T1 a, T2 b) : first(a), second(b) {}
T1 getFirst() const {
return first;
}
T2 getSecond() const {
return second;
}
void show() const {
cout << "(" << first << ", " << second << ")" << endl;
}
};
int main() {
Pair<int, double> p1(7, 3.25);
Pair<const char*, int> p2("marks", 92);
Pair<char, char> p3('x', 'y');
p1.show();
p2.show();
p3.show();
cout << p2.getFirst() << " = " << p2.getSecond() << endl;
return 0;
}Output:
(7, 3.25)
(marks, 92)
(x, y)
marks = 925. Non-Type Parameters and Default Arguments
Template parameters can also be constant values (non-type parameters), such as a size, and can have default arguments, as function parameters do.
#include <iostream>
using namespace std;
template <class T = int, int SIZE = 4> // default type and default size
class Array {
T a[SIZE]; // SIZE is a compile-time constant
public:
Array() {
for (int i = 0; i < SIZE; i++) {
a[i] = T();
}
}
T& operator[](int i) {
return a[i];
}
int size() const {
return SIZE;
}
};
int main() {
Array<double, 3> prices; // 3 doubles
Array<> counts; // defaults: 4 ints
prices[0] = 9.5;
prices[1] = 3.25;
prices[2] = 1.0;
for (int i = 0; i < counts.size(); i++) {
counts[i] = i * i;
}
cout << "prices (" << prices.size() << "):";
for (int i = 0; i < prices.size(); i++) {
cout << " " << prices[i];
}
cout << endl << "counts (" << counts.size() << "):";
for (int i = 0; i < counts.size(); i++) {
cout << " " << counts[i];
}
cout << endl;
return 0;
}Output:
prices (3): 9.5 3.25 1
counts (4): 0 1 4 9Array<double, 3> and Array<double, 5> are different types, because the size is part of the template arguments.
6. Explicit Specialisation
Sometimes one type needs different code. An explicit specialisation provides a separate class for that type, written with template <>.
#include <iostream>
#include <cstring>
using namespace std;
template <class T>
class Compare { // generic version
public:
static bool equal(T a, T b) {
return a == b;
}
};
template <>
class Compare<const char*> { // specialisation for C strings
public:
static bool equal(const char* a, const char* b) {
return strcmp(a, b) == 0;
}
};
int main() {
char s1[] = "hello", s2[] = "hello";
cout << "Compare<int>: " << Compare<int>::equal(5, 5) << endl;
cout << "Compare<const char*>: " << Compare<const char*>::equal(s1, s2) << endl;
cout << "pointer comparison: " << (s1 == s2) << endl; // different arrays
return 0;
}Output:
Compare<int>: 1
Compare<const char*>: 1
pointer comparison: 07. Templates and Inheritance
Class templates can take part in inheritance like any class: a template can be derived from an ordinary class, an ordinary class from a template class, or a template from another template.
template <class T>
class SafeStack : public Stack<T> { // a template derived from a template
// ... adds bounds checking
};
class IntStack : public Stack<int> {}; // an ordinary class from a template class8. Function Templates vs Class Templates
| Function template | Class template |
|---|---|
| a family of functions | a family of classes |
template <class T> T max(T a, T b) | template <class T> class Stack { ... }; |
the type is usually deduced from the arguments: max(3, 4) | the type must be written: Stack<int> s; |
| instantiated when called | instantiated when an object (or the type) is used |
examples: STL algorithms sort, find | examples: STL containers vector, list, map |
Key points to remember
template <class T> class Stack { ... };thenStack<int> s;: the type argument is always written.- Members defined outside:
template <class T> void Stack<T>::push(...). - Several parameters:
template <class T1, class T2>; non-type parameters:template <class T, int N>; defaults allowed. - Explicit specialisation:
template <> class Compare<const char*> { ... };. - All STL containers are class templates.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is a class template? Write a generic stack class and use it with
int,doubleandchar. (10 Marks) - Write: the syntax, the instantiation idea, and the
Stack<T>program with output. - Q2. How are member functions of a class template defined outside the class? Write a program. (5 Marks)
- Write: the
template <class T> ... Vector<T>::form and theVectorprogram. - Q3. Explain class templates with multiple parameters and with non-type parameters. (5 Marks)
- Q4. Differentiate between function templates and class templates. (2.5 Marks)
- Q5. What is template specialisation? (2.5 Marks)