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 19 of 45 · C++

Lesson 26: Class Templates

Duration: 11 min

Class Templates\n\nClass templates let you create generic container‑like types. The Standard Library's std::vector, std::optional, and many others are class templates.\n\n---\n\n## Example: Simple Pair class template with specialization\ncpp\ntemplate <typename T1, typename T2>\nclass Pair {\n T1 first;\n T2 second;\npublic:\n Pair(const T1& a, const T2& b) : first(a), second(b) {}\n const T1& getFirst() const { return first; }\n const T2& getSecond() const { return second; }\n};\n\n// Full specialization for same type – provides a `swap` member\ntemplate <typename T>\nclass Pair<T, T> {\n T a, b;\npublic:\n Pair(const T& x, const T& y) : a(x), b(y) {}\n void swap() { std::swap(a, b); }\n const T& left() const { return a; }\n const T& right() const { return b; }\n};\n\nint main() {\n Pair<int, std::string> p1(42, \"answer\");\n std::cout << p1.getFirst() << ", " << p1.getSecond() << '\\n';\n\n Pair<double, double> p2(1.5, 2.5);\n p2.swap(); // swaps values\n std::cout << p2.left() << " <-> " << p2.right() << '\\n';\n return 0;\n}\n\n\nKey take‑aways:\n- Template parameters can be type, non‑type, or template‑template.\n- Specialization lets you tailor behaviour for particular types.\n- Use static_assert inside the class to enforce compile‑time constraints.\n\n> Tip: When you need a compile‑time constant as a template argument, use std::integral_constant or std::ratio.\n\n---\n\n<Alert type="info">C++20 concepts can also be applied to class templates to constrain the allowed types.

Previous: Lesson 25: Function TemplatesNext: Lesson 27: Standard Template Library (STL) Overview