Modern C++ • C++20 baseline
Function Templates and Type Deduction
Write reusable algorithms that preserve type information without sacrificing compile-time checking.
A function template describes a family of functions parameterized by types or values. The compiler deduces template arguments from function arguments in many common cases. Templates are instantiated at compile time, so diagnostics can be verbose; small constraints and clear interfaces make errors easier to understand.
Key points
- Templates are compiled for concrete types used by the program.
- Avoid unnecessary explicit template arguments when deduction is clear.
Example
#include <iostream>
template <typename T>
constexpr const T& larger(const T& left, const T& right) {
return left < right ? right : left;
}
int main() {
std::cout << larger(4, 9) << '\n';
}
What to expect
9
Practice exercise
Try calling larger with two types that cannot be compared. Improve the API constraint in the next lesson.
Key idea: Templates enable reuse while preserving static types; constrain their valid operations.