Lesson 25 of 45
C++Lesson 25: Function Templates
10 min
Course progress56%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 25 of 45
C++10 min
Keep these ideas in mind as you work through the lesson.
Templates enable you to write generic functions that work with any type. The compiler generates a concrete version for each distinct set of template arguments used.
max template with constexprtemplate <typename T>
constexpr const T& max(const T& a, const T& b) {
return (a < b) ? b : a; // requires `<` operator
}
int main() {
std::cout << max(3, 7) << '\
'; // int
std::cout << max(2.5, 1.3) << '\
'; // double
std::cout << max(std::string(\"a\"), std::string(\"z\")) << '\
'; // std::string
return 0;
}
Constraints (C++20) let you restrict the template to types that satisfy a concept:
template <std::totally_ordered T>
T clamp(T v, T lo, T hi) {
if (v < lo) return lo;
if (v > hi) return hi;
return v;
}
Tip: Prefer
constexprfunctions for compile‑time evaluation when possible.
<Alert type="warning">Template errors can be verbose. Using concepts and requires clauses yields clearer diagnostics.