Templates¶
Templates are the foundation of generic programming in C++. They allow you to write generic functions or classes that work with any arbitrary data type, letting the compiler generate the concrete type-specific implementations at compile time.
1. Function Templates and Argument Deduction¶
Instead of writing identical logic for different data types (e.g. overloading a math helper for int, float, and double), you define a single Function Template.
2. Class Templates and CTAD (C++17)¶
Class templates allow you to define generic data structures (like vectors, arrays, or boxes) that can contain any data type.
Class Template Argument Deduction (CTAD)¶
Before C++17, you always had to specify the template type when instantiating a class template:
3. Template Specialization¶
Sometimes, you need a different implementation for a specific type to optimize performance or fix logic issues. This is handled using Template Specialization.
1. Full Specialization¶
Provides a complete alternative definition for a single specific type.
2. Partial Specialization¶
Provides a specialized implementation for a subset of types (e.g., all pointer types).
4. Non-Type Template Parameters¶
In addition to types (typename), template parameters can accept constant values of certain types (like integers, enums, or references/pointers).
This is widely used to create compile-time sized arrays or configurations.
5. Why Templates Must Live in Headers¶
A common point of confusion is why template implementations are written inside header files (.hpp / .h) rather than separated into .cpp source files.
The Instantiation Mechanism¶
- Compilation Phase: Templates are blueprints, not concrete executable code. The compiler does not compile a template in isolation.
- Usage Phase: When you compile
find_max(10, 20), the compiler must generate (instantiate) a function calledfind_max<int>. - The Problem: To generate that concrete code, the compiler needs to see the full implementation of the template. If the implementation is in a separate
.cppfile, the compiler only sees the declaration and leaves a reference for the linker. - Linker Error: The linker will look for the compiled symbol
find_max<int>, but since the.cpptemplate source was never instantiated during compiling (as it didn't know what types would be used), it fails with anundefined referenceerror.
Rule: Always write both template declarations and definitions in header files.
6. Variadic Templates and Fold Expressions¶
Introduced in C++11, Variadic Templates allow templates to accept an arbitrary number of arguments of any type. C++17 enhanced this with Fold Expressions, allowing you to perform operations on the argument pack using a concise syntax.
Related Guides¶
- Basic Syntax — Constants and static-typing details.
- The STL Containers — The core template containers of the standard library.