C++ function templates
Reuse one type-checked algorithm for different types.
On this page
Functions, comparisons, and return values.
- Reuse one type-checked algorithm for different types.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A function template describes a family of functions. The compiler deduces T from matching arguments and instantiates the needed versions.
This maximum implementation requires that T supports comparison with > and copying its selected value. Mixed argument types need an explicit design decision rather than an accidental conversion.
Code example
#include <iostream>
template <typename T>
T maximum(T left, T right) {
return left > right ? left : right;
}
int main() {
std::cout << maximum(3, 7) << '\n';
std::cout << maximum(2.5, 1.5) << '\n';
}7 2.5
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#include <iostream>template <typename T>T maximum(T left, T right) { return left > right ? left : right;}int main() { std::cout << maximum(3, 7) << '\n'; std::cout << maximum(2.5, 1.5) << '\n';}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Deduce T as int. | left = 3, right = 7 | — | |
| 3 > 7 is false, so choose right. | return = 7 | — | |
| Print the int result. | return = 7 | 7 | |
| Deduce T as double; 2.5 is greater. | return = 2.5 | 7 2.5 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
Cost and common mistakes
One comparison plus copying; O(1) for the primitive types shown.
- maximum(3, 2.5) cannot deduce one T in this declaration.
- Templates do not guarantee that every possible type supports the operations in the body.
Try it yourself
Predict maximum(4, 4).
Reveal answer and reasoning
It returns 4; the comparison is false and the right value is selected.