C++ Templates
Templates let you write code once and use it with many types. Instead of writing maxInt, maxDouble and maxString, you write a single maxOf<T> and the compiler generates a version for each type you use. This is called generic programming, and it is how the entire Standard Template Library (STL) — vector, map, sort and friends — is built.
Function templates
Put template <typename T> in front of a function. T is a placeholder for a type:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << maxOf(3, 9) << "\n"; // T = int
cout << maxOf(2.5, 1.5) << "\n"; // T = double
cout << maxOf(string("pear"), string("apple")) << "\n"; // T = string
cout << maxOf<double>(4, 7.5) << "\n"; // T given explicitly
}9
2.5
pear
7.5
Usually the compiler deduces T from the arguments. In the last call the arguments have different types (int and double), so we name T explicitly. A template works for any type that supports the operations used inside it — here, >.
Multiple type parameters
#include <iostream>
#include <string>
using namespace std;
template <typename K, typename V>
void printPair(const K& key, const V& value) {
cout << key << " => " << value << "\n";
}
template <typename T>
T sumArray(const T arr[], int n) {
T total{}; // value-initialised: 0 for numbers, "" for strings
for (int i = 0; i < n; i++) total += arr[i];
return total;
}
int main() {
printPair("age", 42);
printPair(3.14, string("pi"));
int ints[] = {1, 2, 3, 4};
double ds[] = {0.5, 0.25};
string words[] = {"tem", "pla", "tes"};
cout << sumArray(ints, 4) << " " << sumArray(ds, 2) << " " << sumArray(words, 3) << "\n";
}age => 42
3.14 => pi
10 0.75 templates
Class templates
Classes can be templates too. Here is a tiny fixed-capacity stack that works for any element type:
#include <iostream>
#include <string>
using namespace std;
template <typename T, int Capacity>
class FixedStack {
public:
bool push(const T& value) {
if (count == Capacity) return false;
data[count++] = value;
return true;
}
T pop() { return data[--count]; }
bool empty() const { return count == 0; }
int size() const { return count; }
private:
T data[Capacity];
int count = 0;
};
int main() {
FixedStack<int, 3> numbers;
for (int i = 1; i <= 4; i++) {
cout << "push " << i << ": " << (numbers.push(i) ? "ok" : "full") << "\n";
}
while (!numbers.empty()) cout << numbers.pop() << " ";
cout << "\n";
FixedStack<string, 5> names;
names.push("first");
names.push("second");
cout << names.pop() << ", size now " << names.size() << "\n";
}push 1: ok
push 2: ok
push 3: ok
push 4: full
3 2 1
second, size now 1
Template parameters do not have to be types: int Capacity is a non-type template parameter — a compile-time constant. std::array<int, 5> uses exactly this idea.
Constraining templates with concepts (C++20)
What if someone calls maxOf with a type that has no >? Older compilers produce pages of cryptic errors. C++20 concepts let you state the requirements up front, producing clear messages and enabling overloads by capability:
#include <iostream>
#include <concepts>
#include <string>
using namespace std;
template <typename T>
concept Numeric = integral<T> || floating_point<T>;
template <Numeric T>
T average(T a, T b) {
return (a + b) / 2;
}
// abbreviated syntax: 'auto' parameter constrained by a concept
void describe(integral auto n) { cout << n << " is an integer\n"; }
void describe(floating_point auto x) { cout << x << " is a floating-point number\n"; }
int main() {
cout << average(4, 9) << "\n"; // int: integer division
cout << average(4.0, 9.0) << "\n";
describe(42);
describe(2.5);
// average(string("a"), string("b")); // error: constraints not satisfied
}6
6.5
42 is an integer
2.5 is a floating-point number
How templates are compiled
A template is not code by itself — it is a recipe. When you use maxOf<int>, the compiler instantiates the recipe for int. This has two consequences:
| Consequence | Why |
|---|---|
| No runtime cost | Each instantiation is ordinary, fully optimised code |
| Templates usually live in header files | The compiler needs the full definition wherever the template is used |
Tip: Before writing your own generic container or algorithm, check the standard library. It almost certainly already has a well-tested template for the job.
Test yourself
What does template <typename T> introduce?
- A runtime type check
- A type parameter T
- A new class named T
- A pointer type
Why does maxOf(4, 7.5) fail to deduce T for template<typename T> T maxOf(T, T)?
- Because 7.5 is negative
- The arguments have different types (int and double)
- Templates cannot take numbers
- maxOf is a keyword
What C++20 feature lets you state requirements on template arguments?
- Modules
- Coroutines
- Concepts
- Ranges