Templates in Modern C++¶
Overview¶
Templates enable writing generic, type-independent code in C++. They are the foundation for reusable algorithms and libraries like the STL.
Templates allow you to: - Write a function or class once and reuse it with many types. - Rely on compile-time type deduction for efficiency and safety. - Specialize behavior for certain types when necessary.
Types of Templates¶
C++ provides several kinds of templates:
Function templates — for generic algorithms.
Class templates — for type-parameterized data structures.
Variable templates — for parameterized constants.
Alias templates — for reusable type aliases.
Note
Templates are instantiated at compile time. The compiler generates a concrete version of the template for each unique type combination used.
Quick Comparison¶
Template Type |
Example |
Typical Use |
|---|---|---|
Function template |
|
Generic algorithms or utilities. |
Class template |
|
Data structures (STL containers, smart pointers). |
Variable template |
|
Type-safe constants. |
Alias template |
|
Simplified type aliases. |
Detailed Topics¶
The following sections explore each area of templates in detail:
Interoperability with Generic Code¶
Templates integrate with: - Type traits and concepts (in C++20+) for constraints and static checks. - constexpr and decltype for compile-time computation and type inference.
Example¶
#include <iostream>
template <typename T>
auto multiply(const T& a, const T& b) -> decltype(a * b) {
return a * b;
}
int main() {
std::cout << multiply(3, 5) << '\n'; // int
std::cout << multiply(2.5, 4.0) << '\n'; // double
}
Summary¶
Templates are compile-time generators of code.
They allow zero-cost abstractions and strong type safety.
Modern C++ encourages constrained templates using concepts.
For common generic utilities, prefer STL templates (e.g.,
std::vector).