C++ Class
Templates
Write a class once, then use it with any data type: int, double, string, or your own custom types.
The Problem Without Templates
Imagine you build a Box class that stores an int. Later you need the same Box for double and string. Without templates, you must copy-paste the entire class and change the type: three nearly identical classes to maintain.
class BoxInt { int value; ... }; class BoxDouble { double value; ... }; class BoxString { string value; ... };
What Is a Class Template?
A class template is a blueprint for a family of classes. You write the class with a placeholder type (commonly called T), and the compiler generates a concrete class for each type you actually use.
One Blueprint, Many Types
The Syntax of a Class Template
template <typename T> class Box { private: T value; public: Box(T v) : value(v) {} T get() const { return value; } void set(T v) { value = v; } };
typename vs class Keyword
You will see two forms of the template declaration. Both are identical in meaning for type parameters:
template <typename T> // modern style template <class T> // older style, same effect
| typename | class | |
|---|---|---|
| Meaning | T can be any type | T can be any type |
| Works with primitives? | Yes | Yes |
| Works with classes? | Yes | Yes |
| Convention | Preferred in modern C++ | Common in older code |
Function Templates vs Class Templates
| Function Template | Class Template | |
|---|---|---|
| Parameterizes | A single function | An entire class |
| Type deduction | Automatic from args | Explicit (until C++17 CTAD) |
| Example | max<T>(a, b) | vector<int> |
| Members | Just the function body | Fields, methods, constructors |
| State | Stateless | Can hold data members of type T |
How to Write a Class Template
Example 1: A Pair Template
template <typename T> class Pair { private: T first; T second; public: Pair(T a, T b) : first(a), second(b) {} T getFirst() const { return first; } T getSecond() const { return second; } };
// Usage Pair<int> p1(3, 7); Pair<double> p2(1.5, 2.8); Pair<string> p3("hi", "bye");
Example 2: Two Type Parameters
A template can have more than one type parameter. Here, K is the key type and V is the value type:
template <typename K, typename V> class Entry { private: K key; V value; public: Entry(K k, V v) : key(k), value(v) {} K getKey() const { return key; } V getValue() const { return value; } };
// Usage Entry<string, int> e1("age", 17); Entry<int, double> e2(1, 99.9);
Example 3: A Stack Template
#include <vector> template <typename T> class Stack { private: vector<T> data; public: void push(T val) { data.push_back(val); } T top() const { return data.back(); } void pop() { data.pop_back(); } bool empty() const { return data.empty(); } };
Stack<int> s; s.push(10); s.push(20); // s.top() returns 20
Defining Methods Outside the Class
When you define a member function outside the class body, you must repeat the template header and use the ClassName<T>:: scope prefix:
template <typename T> class Box { T value; public: Box(T v); T get() const; }; // Outside definition template <typename T> Box<T>::Box(T v) : value(v) {} template <typename T> T Box<T>::get() const { return value; }
How Instantiation Works
The Header File Rule
Unlike regular classes, template definitions cannot be split into separate .h and .cpp files in the normal way. The compiler needs to see the full definition at the point of instantiation.
Common Mistakes
Summary at a Glance
| Concept | Details |
|---|---|
| Purpose | Write one class, use with many types |
| Syntax | template <typename T> class Name { ... }; |
| Instantiation | Name<int>, Name<string>, etc. |
| Multiple params | template <typename K, typename V> |
| Outside methods | Repeat template header + Name<T>:: scope |
| File placement | All code in the header (.h) file |
| STL examples | vector<T>, map<K,V>, stack<T> |
Question 1 of 5
Which line correctly begins a class template declaration in C++?
Question 2 of 5
Given the template below, which instantiation creates a Pair that holds two strings?
template <typename T> class Pair { T a; T b; };
Question 3 of 5
Why must template class definitions typically be placed in a header file rather than a .cpp file?
Question 4 of 5
When defining a member function outside a class template, what must you write before the function?
Question 5 of 5
How many type parameters does this template have?
template <typename A, typename B, typename C> class Triple { A x; B y; C z; };