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 26: Class Templates | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 26 of 45

·C++

Lesson 26: Class Templates

11 min

Course progress58%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Template class definition basics
  • Member function templates
  • Template specialization (partial & full)
  • Template aliasing (using) and concepts

Class Templates

Class templates let you create generic container‑like types. The Standard Library's std::vector, std::optional, and many others are class templates.


Example: Simple Pair class template with specialization

template <typename T1, typename T2>
class Pair {
    T1 first;
    T2 second;
public:
    Pair(const T1& a, const T2& b) : first(a), second(b) {}
    const T1& getFirst() const { return first; }
    const T2& getSecond() const { return second; }
};

// Full specialization for same type – provides a `swap` member
template <typename T>
class Pair<T, T> {
    T a, b;
public:
    Pair(const T& x, const T& y) : a(x), b(y) {}
    void swap() { std::swap(a, b); }
    const T& left() const { return a; }
    const T& right() const { return b; }
};

int main() {
    Pair<int, std::string> p1(42, \"answer\");
    std::cout << p1.getFirst() << ", " << p1.getSecond() << '\
';

    Pair<double, double> p2(1.5, 2.5);
    p2.swap(); // swaps values
    std::cout << p2.left() << " <-> " << p2.right() << '\
';
    return 0;
}

Key take‑aways:

  • Template parameters can be type, non‑type, or template‑template.
  • Specialization lets you tailor behaviour for particular types.
  • Use static_assert inside the class to enforce compile‑time constraints.

Tip: When you need a compile‑time constant as a template argument, use std::integral_constant or std::ratio.


<Alert type="info">C++20 concepts can also be applied to class templates to constrain the allowed types.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 25: Function TemplatesContinue to lesson 27Lesson 27: Standard Template Library (STL) OverviewBack to C++ Course curriculum