Module lessons (2/2)
Class Templates
Just like functions, classes can also be parameterized with respect to one or more data types. This allows us to define generic data structures (such as lists, queues, stacks, or wrappers) that work with any data type without duplicating code.
Defining a Class Template
To declare a class template, we use the template <typename T> syntax immediately before the class definition. Inside the class, we can use the type parameter T to define member variables, return types, or member function parameters.
template <typename T>
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
T getValue() const {
return value;
}
};
Instantiation
When creating an object of a class template, we must explicitly specify the type between angle brackets <> (although starting with C++17, the compiler can deduce it in some contexts via Class Template Argument Deduction or CTAD):
Box<int> intBox(10); // T becomes int
Box<double> doubleBox(3.14); // T becomes double
Template Specialization
Sometimes we want a different behavior for a class template when it is instantiated with a specific type. In this case, we define a total specialization using the template <> syntax followed by the class definition specifying the target type:
// Total specialization for the bool type
template <>
class Box<bool> {
private:
bool value;
public:
Box(bool v) : value(v) {}
void printState() {
std::cout << (value ? "True" : "False");
}
};
Try it yourself
Declare a class template named Box that contains a private member named value of type T, a constructor that initializes it, and a public method getValue() const that returns the value.
Show hint
Remember to prepend `template <typename T>` to the `Box` class declaration.
Solution available after 3 attempts
Declare a class template Wrapper<T> with a public member data of type T, a constructor Wrapper(T d), and a print() method that prints data to std::cout. Next, create a total specialization for Wrapper<char> where the print() method prints the character enclosed in single quotes (e.g., 'A' instead of A).
Show hint
Use `template <>` to indicate the total specialization of `Wrapper<char>`.
Solution available after 3 attempts