Function Templates
Templates let you write code that works with any type. Write one template and the compiler stamps out specific versions for int, double, string, or whatever else you throw at it.
Your First Template
template <typename T>T max_of(T a, T b) { return (a > b) ? a : b;}
int main() { std::cout << max_of(3, 7) << std::endl; // 7 (int version) std::cout << max_of(3.14, 2.71) << std::endl; // 3.14 (double version) return 0;}The compiler sees max_of(3, 7) and generates a function max_of<int>(int, int). All at compile time. Zero runtime cost.
Below is what g++ -O2 makes of the two instantiations when they're compiled as standalone functions rather than inlined into main. Hover each call to light up its function. The template itself has no colour because, on its own, it produces no machine code at all.
One template, two functions
x86-64Hover over code lines or mapping badges to see correspondences
The int body works in general-purpose registers with a conditional move; the double body lives in SSE registers, where one maxsd does the whole job. The module "What Your C++ Code Actually Does" comes back to this with symbol names and template bloat.
Template Type Deduction
The compiler usually deduces T from the arguments:
max_of(3, 7); // T = int (deduced)max_of<double>(3, 7); // T = double (explicit)A template is a recipe the compiler uses to bake functions on demand, one per type it encounters. The mechanism is called template instantiation, and the resulting code runs as fast as anything you'd hand-write for that specific type.
Multiple Type Parameters
template <typename T, typename U>auto add(T a, U b) { return a + b;}
auto result = add(3, 4.5); // T=int, U=double, returns doubleTemplate Constraints (C++20)
You can constrain what types are accepted:
#include <concepts>
template <typename T>requires std::integral<T>T gcd(T a, T b) { while (b != 0) { T temp = b; b = a % b; a = temp; } return a;}Try gcd(3.14, 2.71) and you get a readable error pointing at the constraint, rather than the wall of template gibberish you'd otherwise wade through.
The runner below compiles as C++14, so requires and <concepts> aren't available there. You can still see both kinds of error. Without a constraint, max_of on a type with no > produces the classic template error from deep inside the function body; gcd uses the pre-C++20 workaround, a static_assert on a type trait, which fails with the message you wrote.
When to Use Templates
Reach for templates when:
- The algorithm doesn't care about type
- You need zero runtime overhead
- You want type safety, no
void *casts
They're the foundation the entire STL is built on.