01 / 21
<T>

C++ Class
Templates

Write a class once, then use it with any data type: int, double, string, or your own custom types.

C++

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.

Blueprint
You write one definition using a type parameter T.
Instantiation
The compiler generates a real class when you specify a type, e.g. Box<int>.
Type Safety
Each generated class is fully type-checked at compile time: no runtime casting.

One Blueprint, Many Types

Box<T> Class Template Box<int> value: int Box<double> value: double Box<string> value: string stores 42 stores 3.14 stores "hello"

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; }
};
1
template <typename T>: declares a type parameter named T. This line goes right before the class.
2
T replaces every place you would have written a concrete type (int, double, etc.).
3
Usage: write Box<int> to create an integer Box, Box<string> for strings.

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

1
Identify the variable type. Find which type in your class should be flexible (the data type of stored values, for example).
2
Add the template header. Write template <typename T> directly above the class keyword.
3
Replace the concrete type with T. Everywhere you wrote int (or whichever type), write T instead.
4
Instantiate with angle brackets. In your code, write ClassName<int>, ClassName<double>, etc.
5
Keep everything in the header file. Templates must be visible at the point of instantiation, so definitions typically live in .h files.

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

Your Source Code Box<int> b(5); Box<double> d(3.14); Compiler class Box_int int value; int get() const; class Box_double double value; double get() const; Generated at compile time Generated at compile time

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.

✕ Wrong
Declaration in Box.h, definition in Box.cpp: linker error.
✓ Correct
Put the entire class (including method bodies) in Box.h.

Common Mistakes

✕ Forgetting template header
Writing class Box without template <typename T> above it. The compiler treats T as an unknown identifier.
✕ Splitting into .cpp
Putting template method definitions in a .cpp file causes linker errors. Keep everything in the header.
✕ Missing <T> in scope
Writing Box::get() outside the class instead of Box<T>::get(). The compiler cannot resolve the template.

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; };