Classes can be templates too. Here's a tiny box that can hold one value of any type:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T get() const { return value; }
void set(T v) { value = v; }
};
int main() {
Box<int> a(42);
Box<string> b("hello");
a.set(a.get() + 1);
cout << a.get() << " " << b.get() << "\n";
return 0;
}Output
43 hello
A simple stack of anything
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
class Stack {
vector<T> items;
public:
void push(const T& x) { items.push_back(x); }
void pop() { items.pop_back(); }
T top() const { return items.back(); }
bool empty() const { return items.empty(); }
int size() const { return items.size(); }
};
int main() {
Stack<string> history;
history.push("home");
history.push("news");
history.push("sports");
cout << "Pages: " << history.size() << "\n";
history.pop();
cout << "Back to: " << history.top() << "\n";
return 0;
}Output
Pages: 3 Back to: news
Templates with two types
#include <iostream>
#include <string>
using namespace std;
template <typename K, typename V>
struct Entry {
K key;
V value;
};
int main() {
Entry<string, double> e = {"pi", 3.14};
Entry<int, char> f = {7, 'z'};
cout << e.key << "=" << e.value << ", " << f.key << "=" << f.value << "\n";
return 0;
}Output
pi=3.14, 7=z
Tip: You won't write class templates every day, but understanding them helps you read error messages from the STL – and use it with confidence.