C++ ยท Chapter 40 of 49

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.

Example 1 (cpp)
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);
}
Output
7 2.5

The 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.
๐Ÿ’ก Note: Template error messages can be long and confusing โ€” read from the top, where the actual mismatch is usually reported.

๐Ÿ“ Quick Quiz

1. Which keyword introduces a generic type parameter?

2. std::vector is an example of a:

3. Templates are resolved: