What is a template in C++, and why does it matter?
A template is a blueprint the compiler stamps out for any type you plug in — write the logic once, and it works for int, string, or your own class, with no loss of type safety.
Templates are C++'s tool for generic programming: code parameterised by type instead of by value. You write the algorithm or container once, against a placeholder type, and the compiler generates a concrete version for each type you actually use.
template <typename T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}
maximum(3, 7); // compiler stamps out maximum<int>
maximum(2.5, 1.5); // and a separate maximum<double>
maximum(string("a"), string("b")); // and one for string
template <typename T>introducesTas a stand-in for "some type decided later".- The compiler performs instantiation: each distinct
Tyou use produces its own compiled function or class — so there's no runtime dispatch cost, unlikevirtual. - This is exactly how the STL works:
vector<int>,vector<string>, andmap<string,int>are all instantiations of the same template.
Why it matters: before templates you either wrote the same code once per type (error-prone) or threw away type safety with void* and casts (C's approach). Templates give you both reuse and compile-time type checking.
Tip: virtual and templates are the two faces of polymorphism — virtual resolves at runtime (one function, many object types), templates resolve at compile time (many functions, generated per type). RE tip: templated code produces separate, duplicated machine code per instantiation, which is why C++ binaries built on the STL are often large.
Go deeper:
Templates — cppreference — function and class templates in full.
Template (C++) — Wikipedia — the feature with worked examples.
Generic programming — Wikipedia — the broader idea templates implement.