Lesson 18 of 45 · C++
Lesson 25: Function Templates
Duration: 10 min
Lesson 18 of 45 · C++
Duration: 10 min
max template with constexpr\ncpp\ntemplate <typename T>\nconstexpr const T& max(const T& a, const T& b) {\n return (a < b) ? b : a; // requires `<` operator\n}\n\nint main() {\n std::cout << max(3, 7) << '\\n'; // int\n std::cout << max(2.5, 1.3) << '\\n'; // double\n std::cout << max(std::string(\"a\"), std::string(\"z\")) << '\\n'; // std::string\n return 0;\n}\n\n\nConstraints (C++20) let you restrict the template to types that satisfy a concept:\ncpp\ntemplate <std::totally_ordered T>\nT clamp(T v, T lo, T hi) {\n if (v < lo) return lo;\n if (v > hi) return hi;\n return v;\n}\n\n\n> Tip: Prefer constexpr functions for compile‑time evaluation when possible.\n\n---\n\n<Alert type="warning">Template errors can be verbose. Using concepts and requires clauses yields clearer diagnostics.