Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 18 of 45 · C++

Lesson 25: Function Templates

Duration: 10 min

Function Templates\n\nTemplates 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.\n\n---\n\n## Example: 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.

Previous: Lesson 24: Abstract Classes and InterfacesNext: Lesson 26: Class Templates