C++ Templates
Templates let you write generic functions and classes that work with any data type, determined at compile time. `template<typename T>` before a function or class definition introduces a type parameter T.
The standard library itself is built almost entirely on templates โ `std::vector<int>`, `std::vector<std::string>`, and so on are all instantiations of the same generic vector template.
Function templates
`template<typename T> T maxVal(T a, T b) { return a > b ? a : b; }` works for int, double, or any type supporting `>`, without writing separate overloads.
Class templates
`template<typename T> class Box { T value; };` lets you create `Box<int>` or `Box<std::string>` from one class definition.
template<typename T>
T maxVal(T a, T b) {
return a > b ? a : b;
}
int main() {
std::cout << maxVal(3, 7) << " " << maxVal(2.5, 1.5);
}7 2.5The same template works for both int and double arguments.
Key points
- template<typename T> declares a generic type parameter.
- Templates work for both functions and classes.
- The compiler generates concrete code for each type used.
- STL containers like vector are all class templates.
