Loading lessons...
Function Templates
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
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
using namespace std;
int main() {
cout << max(3, 8) << "\n"; // int version
cout << max(2.5, 1.5) << "\n"; // 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 > operator, so a type with > works and a type without it produces a compile error.
TL;DR
- A function template declares one function for many types.
template <typename T>makesTa placeholder type.- The compiler creates a matching version for each type you call with.
- The concrete type must support whatever the body does.