Template classes
- C++ course
- Intermediate
- Lesson 49/116
- 5 min
Learn to write generic classes with template<typename T>.
Template class
A template class is a class that takes a type parameter. Declaration: template <typename T> class Box { T value; };. The T value member depends on the class's type parameter.
Instantiation: Box<int> b;. The type goes in angle brackets. The compiler generates a separate class for each type. Box<int> and Box<double> are two distinct classes. Member functions also use T; for example T getValue().
Template class members
Member functions of a template class use T. Like T getValue() { return value; }. The member function is called on an instance: Box<int> b(42); b.getValue().
The constructor can also take T: Box(T v) : value(v) {}. Here : value(v) is the initializer list that constructs the member. Box<int> b(42) creates an instance with value=42. b.getValue() returns 42. Template classes provide type-safe encapsulation.
Practice Write the Box template class
Write template <typename T> class Box. Private member T value, constructor Box(T v) : value(v) {}, T getValue() returns the value. In main write Box<int> b(42); and std::cout << b.getValue() << std::endl;.
Starter code
#include <iostream>
// write the Box template class: T value, T getValue()
int main() {
// create a Box<int> instance and print getValue()
return 0;
}Sample solution
#include <iostream>
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T getValue() { return value; }
};
int main() {
Box<int> b(42);
std::cout << b.getValue() << std::endl;
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the class declaration
template <typename T> class ____ { T value; };
template <typename T> class Box { T value; };
Explanation: Class names use PascalCase: Box.
2 Match member to role
| Term | Meaning |
|---|---|
Box<int> |
Instance of type int |
T value |
Type-parametered member |
getValue() |
Member function |
b.getValue() |
Call on instance |
3 How is Box<double> declared?
template <typename T> class Box;- Box double b;
- Box<b> double;
- Box<double> b; Correct answer
- double<Box> b;
Explanation: Box<double> b; puts the type in angle brackets.