6.1 Function Templates
Without templates you would need a separate max() function for int, double, char, and every other type, all with identical logic.
A function template lets you write that logic once using a placeholder type, conventionally named T; the compiler then generates a specific version for whichever type you actually use, entirely at compile time, with zero runtime cost.
template <typename T>
T maxVal(T a, T b) {
return (a > b) ? a : b;
}
maxVal(3, 7); // instantiates an int version
maxVal(2.5, 1.1); // instantiates a double version
6.2 Class Templates
Just like functions, entire classes can be templated. This is exactly how the Standard Template Library's containers, like vector, work internally: one class definition that can hold ints, strings, or your own custom objects, all fully type-checked at compile time.
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T get() { return value; }
};
Box<int> b1(10);
Box<string> b2("hi");
6.3 Templates + STL
Templates are the reason the Standard Template Library can be both generic and fast: its containers and algorithms are written once as templates and then specialized by the compiler for whatever type you plug in, with no runtime overhead compared to hand-writing a type-specific version yourself.
vector<int> nums = {1, 2, 3};
vector<string> names = {"Ann", "Bob"};
// Same vector template, two completely different high-performance compiled types!