Lesson 19 of 45 · C++
Lesson 26: Class Templates
Duration: 11 min
Lesson 19 of 45 · C++
Duration: 11 min
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.