C++ function templates

Reuse one type-checked algorithm for different types.

C++
#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';
}
Output
7
2.5

Explanation

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.

Explore the dry run
Guided walkthroughReady
1#include <iostream>
2template <typename T>
3T maximum(T left, T right) {
4 return left > right ? left : right;
5}
6int main() {
7 std::cout << maximum(3, 7) << '\n';
8 std::cout << maximum(2.5, 1.5) << '\n';
9}

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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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

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.

Further reading