C++ Class Templates
A class template is a pattern for a class that the compiler fills in with a chosen type. One written class can hold values of many types.
A box for one value
Box holds one value of the chosen type. An int box and a string box print their own values.
#include <iostream>
#include <string>
template <typename T>
class Box {
public:
Box(T value) : value_(value) {}
T get() const { return value_; }
private:
T value_;
};
int main() {
Box<int> numbers(42);
Box<std::string> word(std::string("crate"));
std::cout << "Number box: " << numbers.get() << "\n";
std::cout << "Word box: " << word.get() << "\n";
return 0;
}A pair of two values
Pair holds two values of one type. Its print method shows both values on one line.
#include <iostream>
#include <string>
template <typename T>
class Pair {
public:
Pair(T first, T second) : first_(first), second_(second) {}
void print() const {
std::cout << first_ << " and " << second_ << "\n";
}
private:
T first_;
T second_;
};
int main() {
Pair<int> scores(10, 20);
Pair<std::string> names(std::string("Ana"), std::string("Bo"));
scores.print();
names.print();
return 0;
}A member defined outside the class
The get method is declared inside the class and defined below it. The outside definition repeats the template header.
#include <iostream>
#include <string>
template <typename T>
class Box {
public:
Box(T value) : value_(value) {}
T get() const;
private:
T value_;
};
template <typename T>
T Box<T>::get() const {
return value_;
}
int main() {
Box<int> count(7);
Box<std::string> label(std::string("sealed"));
std::cout << "Count: " << count.get() << "\n";
std::cout << "Label: " << label.get() << "\n";
return 0;
}Example
#include <iostream>
#include <string>
template <typename T>
class Pair {
public:
Pair(T first, T second) : first_(first), second_(second) {}
void print() const {
std::cout << first_ << " / " << second_ << "\n";
}
private:
T first_;
T second_;
};
int main() {
Pair<int> rounds(3, 5);
Pair<std::string> cities(std::string("Oslo"), std::string("Lima"));
rounds.print();
cities.print();
return 0;
}Key points
- A class template names its type parameter in a template header above the class.
- The chosen type goes in angle brackets when an object is made.
- Members written with the type parameter change type with each use.
- A member function can be defined outside the class body.
- An outside definition repeats the template header and names the class with its parameter.
- Each type used with the template gets its own version of the class.
In this example, one Pair template builds two kinds of pair. The int pair prints its two scores. The string pair prints its two city names.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How is the type chosen when an object of a class template is made?