C++ / CHAPTER 08
Templates and meaningful type requirements
AdvancedWrite reusable algorithms without hiding the operations they require.
By the end of this chapter
- Read type deduction
- State template requirements
- Avoid returning references to temporary arguments
The idea
A function template describes a family of functions selected from the argument types. Reuse succeeds only when the operations used by the body are supported for those types. A template that compares and returns a copied value requires an appropriate comparison and copy behavior. A generic spelling does not make every possible type a valid argument.
Template deduction also connects parameters. If two parameters both use the same T, passing unrelated argument types can fail deduction rather than automatically choosing a common type. Decide whether a single shared type is the contract you want. Return by value when the result must own its lifetime; returning a reference to an argument becomes dangerous when callers supply temporaries or later destroy the arguments.
#include <iostream>
template<class T>
T larger(T a, T b) { return a < b ? b : a; }
int main() {
std::cout << larger(3, 8) << ' ' << larger(2.5, 1.5);
}8 2.5
Each call deduces one T shared by both arguments.
Try it yourself
Implement a generic clamp returning a value, with a documented ordering requirement and valid lower/upper bounds.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING