Learn C++
#include "templates/function_templates.hpp"

Function Templates in C++

//concept

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.

//how it works
1

One definition, many types

template <typename T> stamps out a type-correct copy per call-site type — write once, instantiate everywhere.

2

Deduction from arguments

T is inferred from what you pass; mixed types (int, double) fail deduction unless you specify T explicitly.

3

Compile-time duck typing

The body must compile for each T used — calling .size() inside requires T to have size(), checked per instantiation.

4

Headers only

Templates must be visible at every use, so they live in headers — the compiler can't instantiate what it can't see.

//example
#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;
}
Output
7
b
1max2(3, 7) deduces T=int and instantiates an int version returning 7.
2The string call instantiates a second copy for std::string, where > means lexicographic — b wins.
3One template definition produced two fully type-safe functions with no runtime overhead.
//use cases
Generic max/min/swap/clamp utilities working for every comparable type
STL-style algorithms decoupled from container and element types
Explicit max2<double>(3, 7) calls where mixed arguments confuse deduction
Header-only utility libraries distributed as pure templates

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.