Function Templates in C++
A function template writes an algorithm once for every type: template <typename T> T max2(T a, T b) compiles a fresh max2<int>, max2<double>, ... on demand from each call site. One definition replaces whole families of overloads, with zero run-time cost — instantiation happens at compile time.
The compiler deduces T from the arguments (max2(3, 7) → int), and fails the call if the body doesn't compile for the deduced type — duck typing checked at compile time. Explicit arguments (max2<double>(3, 7)) resolve ambiguity when deduction disagrees.
One definition, many types
template <typename T> stamps out a type-correct copy per call-site type — write once, instantiate everywhere.
Deduction from arguments
T is inferred from what you pass; mixed types (int, double) fail deduction unless you specify T explicitly.
Compile-time duck typing
The body must compile for each T used — calling .size() inside requires T to have size(), checked per instantiation.
Headers only
Templates must be visible at every use, so they live in headers — the compiler can't instantiate what it can't see.
#include <iostream>#include <string> template <typename T>T max2(T a, T b) { return (a > b) ? a : b; } int main() { std::cout << max2(3, 7) << std::endl; std::cout << max2(std::string("a"), std::string("b")) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.