Class templates are a cornerstone of generic programming in C++. They allow you to create classes that can work with different data types without repeating code. This powerful feature enhances code reusability and flexibility.
A class template is a blueprint for creating classes that can operate on various data types. It's defined using the template
keyword, followed by template parameters enclosed in angle brackets.
template <typename T>
class ClassName {
// Class members using type T
};
Here, T
is a placeholder for the actual data type, which is specified when the class is instantiated.
Let's explore a practical example of a class template for a simple stack data structure:
template <typename T>
class Stack {
private:
vector<T> elements;
public:
void push(T const& element) {
elements.push_back(element);
}
T pop() {
if (elements.empty()) {
throw out_of_range("Stack<T>::pop(): empty stack");
}
T top = elements.back();
elements.pop_back();
return top;
}
bool empty() const {
return elements.empty();
}
};
This Stack
class can now be used with any data type:
Stack<int> intStack;
intStack.push(5);
intStack.push(10);
Stack<string> stringStack;
stringStack.push("Hello");
stringStack.push("World");
Class templates can have multiple parameters, allowing for even more flexibility:
template <typename T, typename U>
class Pair {
T first;
U second;
public:
Pair(T f, U s) : first(f), second(s) {}
// ... other methods
};
Pair<int, string> myPair(1, "One");
Sometimes, you might want to provide a specialized implementation for a specific data type. This is called template specialization:
template <>
class Stack<bool> {
// Specialized implementation for bool
};
For more details on this topic, check out the guide on C++ Template Specialization.
ElementType
instead of just T
).Class templates are a powerful feature in C++ that enable generic programming. They allow you to write flexible, type-safe code that works with multiple data types. By mastering class templates, you can significantly improve your C++ programming skills and create more efficient, reusable code.
To further enhance your C++ knowledge, explore related topics such as C++ Function Templates and C++ Variadic Templates.