Function Templates
Prerequisites: Level 1 — Beginner
A template is written once and works with any type, substituted in by the compiler at the point it's actually used — C++'s equivalent of Java's generics, resolved entirely at compile time with zero runtime overhead.
template<typename T>
T max(T a, T b) {
return a > b ? a : b;
}
std::cout << max(3, 7) << std::endl; // 7 — T is int
std::cout << max(3.5, 2.1) << std::endl; // 3.5 — T is double
std::cout << max<std::string>("a", "b") << std::endl; // explicit T
Each distinct type used with a template causes the compiler to generate a separate, fully-specialized version of the function behind the scenes — this is why templates carry no runtime cost, at the expense of a larger compiled binary and longer compile times.
Practice
Write a function template T sum(T a, T b, T c) that adds three
values of the same type.
Show solution
template<typename T>
T sum(T a, T b, T c) {
return a + b + c;
}