Function and Class Templates
Write code once, let the compiler stamp out a version for every type
max for int, another for double, and yet another for std::string, you write a single generic version parameterised on the type. When you use it, the compiler generates the concrete function or class it needs. This is C++'s core mechanism for generic programming, and the entire Standard Template Library (STL) is built on it.
- write function templates with one or more type parameters,
- let the compiler deduce template arguments, or supply them explicitly,
- write class templates such as a generic
PairorStack, - use non-type template parameters (like a compile-time size),
- explain what instantiation is and why template code lives in headers.
1. What problem do templates solve?
Imagine you need a function that returns the larger of two values. Without templates you end up copying the same logic for every type:
int maxOf(int a, int b) { return (a > b) ? a : b; }
double maxOf(double a, double b) { return (a > b) ? a : b; }
std::string maxOf(std::string a, std::string b) { return (a > b) ? a : b; }
The bodies are identical except for the type. That is duplication waiting to rot: fix a bug in one, forget the others. A template lets you describe the shape of the code and leave the type as a blank to be filled in later.
Analogy: think of a cookie cutter. The cutter is not a cookie; it is a shape. Press it into dough (an int) and you get an int-shaped function; press it into a different dough (a std::string) and you get a string-shaped one. The cutter (the template) is written once; the compiler stamps out the concrete cookies (the actual functions) on demand.