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.
Lesson 26 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
Class templates let you create generic container‑like types. The Standard Library's std::vector, std::optional, and many others are class templates.
Pair class template with specializationtemplate <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:
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_constantorstd::ratio.
<Alert type="info">C++20 concepts can also be applied to class templates to constrain the allowed types.