Lesson 156 +10 XP

Function Templates

A function template is a function definition that works with many types. You write the body once with a T placeholder, and the compiler builds a matching version for each type you actually call it with.

One function, many types

Code

cpp
template <typename T>

### T max(T a, T b) {
  return (a > b) ? a : b;
}

Pass int arguments and T becomes int; pass double arguments and T becomes double. The same body serves any type that supports the comparison.

Calling it

Code

cpp
using namespace std;

int main() {
  cout << max(3, 8) << "
";     // int version
  cout << max(2.5, 1.5) << "
"; // double version
  return 0;
}

There are no hand-written int and double overloads anywhere. One template plus the types you use, and the compiler generates a matching function for each call.

The type must support the operations

The type you use must satisfy the operation in the body. max needs the &gt; operator, so a type with &gt; works and a type without it produces a compile error.

TL;DR

  • A function template declares one function for many types.
  • template &lt;typename T&gt; makes T a placeholder type.
  • The compiler creates a matching version for each type you call with.
  • The concrete type must support whatever the body does.