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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 25: Function Templates | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Template syntax and parameters
  • Template argument deduction
  • Explicit template instantiation
  • Common pitfalls (type deduction failures)

Function Templates

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.


Example: max template with constexpr

template <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 constexpr functions for compile‑time evaluation when possible.


<Alert type="warning">Template errors can be verbose. Using concepts and requires clauses yields clearer diagnostics.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 24: Abstract Classes and InterfacesContinue to lesson 26Lesson 26: Class TemplatesBack to C++ Course curriculum