Loading lessons...
Class Templates
Class Templates
Just like functions, classes can be templated. One class template produces a different real class for every type you put in.
A template version of a class
template <typename T>
class Box {
public:
T value;
Box(T v) : value(v) {}
};
T stands for the type of whatever the box holds. When you supply a concrete type, the template becomes a real class you can build objects from.
Declaring an object
Box<int> intBox(5); // a box that holds an int
Box<double> dBox(6.5); // a box that holds a double
The type in angle brackets completes the template. intBox.value is an int; the other box's value gets its own type.
Member functions in the template
template <typename T>
class Box {
public:
T value;
Box(T v) : value(v) {}
T get() { return value; }
};
Member functions defined inside the template can use T just like the data members. Every instantiation - Box<int>, Box<string>, and so on - gets a compiled get.
Same template, different classes
Box<int> and Box<string> are two different, unrelated classes, even though one template made both.
TL;DR
- A class template uses the placeholder
Tinside the class body. - Instantiate with a concrete type:
Box<int> b;. - A separate class is generated for each type used.
- Member functions inside the template can use the placeholders.