Class Templates
Learn how to create generic classes that work with any data type using C++ class templates
Learn how to write classes that work with any data type using templates, the foundation of modern C++ generic programming.
A Simple Example
#include <iostream>
#include <string>
template <typename T>
class Box {
private:
T value;
public:
Box(T val) : value{val} {}
T getValue() const {
return value;
}
void setValue(T val) {
value = val;
}
void display() const {
std::cout << "Box contains: " << value << "\n";
}
};
int main() {
Box<int> intBox{42};
Box<double> doubleBox{3.14};
Box<std::string> stringBox{"Hello"};
intBox.display(); // Box contains: 42
doubleBox.display(); // Box contains: 3.14
stringBox.display(); // Box contains: Hello
return 0;
}
Breaking It Down
Template Declaration - template <typename T>
- What it does: Declares T as a placeholder type that will be filled in later
- typename vs class: Both work identically for type parameters (typename is preferred)
- Remember: This line goes before the class definition
- Think of it as: A blueprint variable that gets replaced with actual types
Using the Type Parameter - T value;
- What it does: Uses T anywhere you would normally write a concrete type like int or string
- Flexibility: T can be int, double, string, or any custom class
- Type safety: The compiler checks that all operations on T are valid
- Remember: T is just a placeholder name - you could use U, Type, or ElementType
Template Instantiation - Box<int> intBox{42};
- What it does: Creates a concrete class by replacing T with int
- Compilation: The compiler generates a complete Box<int> class at compile time
- Performance: No runtime overhead - as fast as writing a separate class for each type
- Remember: Each type instantiation creates a distinct class
Member Functions in Templates
- Return types: Can use T as return type (T getValue() const)
- Parameters: Can use T as parameter type (void setValue(T val))
- Const correctness: Works normally with template types
- Remember: All member functions automatically have access to T
Why This Matters
- Class templates are the foundation of the entire Standard Template Library (STL). Every vector, map, and container you use is built on class templates.
- Understanding them lets you create flexible, type-safe data structures like custom containers, smart pointers, and generic utilities that eliminate code duplication while maintaining performance.
Critical Insight
Class templates are not compiled until you actually use them with a specific type. This means template errors only appear when you instantiate the template, not when you write it.
The compiler generates a completely separate class for each type you use - Box<int> and Box<double> are as different as Car and Bicycle. They just happen to have the same structure. This is called "template instantiation" and happens at compile time with zero runtime cost.
Best Practices
Put templates in header files: Unlike regular classes, template definitions must be in headers because the compiler needs the full definition to generate code for each type.
Use meaningful template parameter names: While T is conventional for single type parameters, use descriptive names like KeyType and ValueType for multiple parameters.
Document type requirements: If your template requires specific operations (like operator<), document this clearly in comments.
Keep templates simple: Start with simple templates and add complexity only when needed. Complex templates are harder to debug.
Common Mistakes
Forgetting template syntax in implementation: When defining member functions outside the class, you need template <typename T> before each function and use ClassName<T>:: not just ClassName::.
Assuming all types work: Your template might use operations (like < or <<) that not all types support. This causes cryptic errors during instantiation.
Separating declaration and definition: Unlike regular classes, you cannot put template declarations in .h and implementations in .cpp files.
Late error detection: Template errors appear when you instantiate with a specific type, not when you write the template, making them harder to debug.
Debug Challenge
This template class has a bug when defining a member function outside the class. Click the highlighted line to fix it:
Quick Quiz
- What happens when you use Box
and Box in the same program?
- Where should you typically put class template definitions?
- When are template errors detected by the compiler?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once