Templates & Generic Programming
Write code once for any type — the power behind the STL and modern C++ metaprogramming.
How do you write a max(a, b) function that works for int, float, and
string without writing three different versions? In C++, you use
Templates. This is the foundation of Generic Programming.
A template is not code yet — it is a recipe the compiler follows. Each time you call it with a new type, the compiler stamps out a concrete version; call it again with a type it has already seen and it reuses what it built. Step through the call sites below to watch the instantiations appear.
template <class T>
T myMax(T a, T b) {
return a > b ? a : b;
}What is a Template?
A template is a blueprint for a function or a class. The compiler uses this blueprint to generate the actual code only when you use the function with a specific type. This is called instantiation.
// A generic function template
template <typename T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// Compiler generates int version:
int i = myMax(10, 20);
// Compiler generates double version:
double d = myMax(3.14, 2.71);
}Why use Templates?
- Code Reuse: Write logic once and use it for any type that supports the
required operations (like the
>operator in ourmaxexample). - Performance: Because templates are expanded at compile-time, there is zero runtime overhead. The code generated is as fast as if you had written it by hand for that specific type.
- Type Safety: The compiler checks that the type you provide actually supports the operations used in the template.
The STL connection
The C++ Standard Template Library (STL) is built entirely on templates.
std::vector<T>, std::map<K, V>, and algorithms like std::sort are all
templates that can be used with any data type.
Takeaways
- Templates allow for type-independent, generic code.
- They are resolved at compile-time, ensuring maximum performance.
- They power the entire C++ standard library (STL).