Module 7 · Templates, Exceptions, Namespaces and Files — topic 1 of 4
Templates
Write a function or class once and use it with any type. Learn function templates, class templates, type deduction, non-type parameters and specialisation.
Learning objectives
- Write function and class templates
- Rely on and override template argument deduction
- Use non-type template parameters and full specialisation
Definition
A template is a blueprint from which the compiler generates functions or classes for specific types (or values) at compile time; this is called template instantiation.
Introduction
Without templates you would write max_int, max_double and max_string. A template writes the logic once with a placeholder type T; the compiler generates each version when it is used.
The entire STL — vector, map, sort, find — is built from templates.
Why it matters
Templates give type-safe generic code with no run-time cost.
Reading STL error messages and writing reusable utilities both require understanding templates.
Detailed explanation
template <typename T> T max_of(T a, T b) { return a > b ? a : b; } — typename and class are interchangeable here.
Calls deduce T from the arguments: max_of(3, 7) uses int. When arguments disagree (max_of(3, 7.5)) deduction fails; specify the type explicitly: max_of<double>(3, 7.5).
A class template: template <typename T> class Stack { std::vector<T> items_; ... }; used as Stack<int>.
Non-type parameters take values: template <typename T, std::size_t N> class FixedArray (like std::array<T, N>).
Specialisation provides a custom implementation for a specific type: template <> class Printer<bool> { ... };.
Template code must usually be in headers, because the compiler needs the full definition to instantiate it in each translation unit.
Syntax
- Template definitions belong in headers.
- Each distinct T produces separate code.
- C++20 concepts can restrict which types are allowed.
Code examples
A function template
7 2.5 pear 7.5
A class template
three two one
More examples
Non-type parameters and specialisation
sum of last 3: 120 42 is int 4.2 is double c is unknown
Step-by-step explanation
Ring<int, 3>stores only the last 3 values in a fixed array; N is a compile-time value.- Adding 10..50 leaves 40, 50, 30 in the ring: sum 120.
TypeNameis specialised for int and double; other types use the primary template.describe('c')instantiatesTypeName<char>, which falls back to "unknown".
Expected output
Running “Non-type parameters and specialisation” prints exactly:
Practical applications
- Every STL container and algorithm is a template.
- Numeric libraries template over float/double precision.
- Embedded code uses non-type parameters for buffer sizes without heap allocation.
Best practices
- Keep templates in headers.
- Give template parameters meaningful names for complex templates.
- Use concepts (C++20) or static_assert to give clearer errors.
Common mistakes
Template definition only in a .cpp file
Avoid
Prefer
Other files can't instantiate a template whose definition they cannot see; you get undefined-reference link errors.
Mixed-type arguments
Avoid
Prefer
Deduction gives T = int from 3 and T = double from 7.5 — a conflict.
Important notes
- Template error messages can be long; read the first error and the line in your code that triggered instantiation.
- C++17 class template argument deduction lets you write
std::pair p(1, 2.5);without<int, double>.
Key takeaways
- Templates generate code per type at compile time.
- Deduction picks T from arguments; specify it when they conflict.
- Specialisation customises behaviour for specific types.
Try it yourself
- 1Write a function template
averagefor a std::vector<T> returning double. - 2Write a class template
Pair<A, B>with aswap()returningPair<B, A>.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
10 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhy are template definitions usually placed in header files?
- ModerateWhy doesn't `max_of(3, 7.5)` compile for `template <typename T> T max_of(T a, T b);`?