Skip to content

Module 7 · Templates, Exceptions, Namespaces and Files — topic 1 of 4

Templates

Write a function or class once and use it with any type. Learn function templates, class templates, type deduction, non-type parameters and specialisation.

Beginner 16 min read·Lesson 27 of 40 in C++ Programming

Learning objectives

  • Write function and class templates
  • Rely on and override template argument deduction
  • Use non-type template parameters and full specialisation

Definition

A template is a blueprint from which the compiler generates functions or classes for specific types (or values) at compile time; this is called template instantiation.

Introduction

Without templates you would write max_int, max_double and max_string. A template writes the logic once with a placeholder type T; the compiler generates each version when it is used.

The entire STL — vector, map, sort, find — is built from templates.

Why it matters

Templates give type-safe generic code with no run-time cost.

Reading STL error messages and writing reusable utilities both require understanding templates.

Detailed explanation

template <typename T> T max_of(T a, T b) { return a > b ? a : b; } — typename and class are interchangeable here.

Calls deduce T from the arguments: max_of(3, 7) uses int. When arguments disagree (max_of(3, 7.5)) deduction fails; specify the type explicitly: max_of<double>(3, 7.5).

A class template: template <typename T> class Stack { std::vector<T> items_; ... }; used as Stack<int>.

Non-type parameters take values: template <typename T, std::size_t N> class FixedArray (like std::array<T, N>).

Specialisation provides a custom implementation for a specific type: template <> class Printer<bool> { ... };.

Template code must usually be in headers, because the compiler needs the full definition to instantiate it in each translation unit.

Syntax

C++
template <typename T>
T max_of(T a, T b) { return a > b ? a : b; }
template <typename T>
class Stack {
public:
void push(const T& v) { items_.push_back(v); }
T pop() { T v = items_.back(); items_.pop_back(); return v; }
bool empty() const { return items_.empty(); }
private:
std::vector<T> items_;
};
  • Template definitions belong in headers.
  • Each distinct T produces separate code.
  • C++20 concepts can restrict which types are allowed.

Code examples

A function template

C++
#include <iostream>
#include <string>
template <typename T>
T max_of(T a, T b) { return a > b ? a : b; }
int main() {
std::cout << max_of(3, 7) << ' ' << max_of(2.5, 1.5) << ' ' << max_of<std::string>("pear", "apple") << '\n';
std::cout << max_of<double>(3, 7.5) << '\n';
return 0;
}
Output
7 2.5 pear
7.5

A class template

C++
#include <iostream>
#include <string>
#include <vector>
template <typename T>
class Stack {
public:
void push(const T& v) { items_.push_back(v); }
T pop() { T v = items_.back(); items_.pop_back(); return v; }
bool empty() const { return items_.empty(); }
private:
std::vector<T> items_;
};
int main() {
Stack<std::string> s;
for (const char* w : {"one", "two", "three"}) s.push(w);
while (!s.empty()) std::cout << s.pop() << ' ';
std::cout << '\n';
return 0;
}
Output
three two one

More examples

Non-type parameters and specialisation

C++
#include <iostream>
template <typename T, int N>
class Ring {
public:
void add(T v) { data_[next_ % N] = v; ++next_; }
T sum() const {
T s{};
int n = next_ < N ? next_ : N;
for (int i = 0; i < n; ++i) s += data_[i];
return s;
}
private:
T data_[N]{};
int next_ = 0;
};
template <typename T>
struct TypeName { static const char* get() { return "unknown"; } };
template <> struct TypeName<int> { static const char* get() { return "int"; } };
template <> struct TypeName<double> { static const char* get() { return "double"; } };
template <typename T>
void describe(T value) { std::cout << value << " is " << TypeName<T>::get() << '\n'; }
int main() {
Ring<int, 3> last3;
for (int i = 1; i <= 5; ++i) last3.add(i * 10);
std::cout << "sum of last 3: " << last3.sum() << '\n';
describe(42);
describe(4.2);
describe('c');
return 0;
}
Output
sum of last 3: 120
42 is int
4.2 is double
c is unknown

Step-by-step explanation

  • Ring<int, 3> stores only the last 3 values in a fixed array; N is a compile-time value.
  • Adding 10..50 leaves 40, 50, 30 in the ring: sum 120.
  • TypeName is specialised for int and double; other types use the primary template.
  • describe('c') instantiates TypeName<char>, which falls back to "unknown".

Expected output

Running “Non-type parameters and specialisation” prints exactly:

TextOutput
sum of last 3: 120
42 is int
4.2 is double
c is unknown

Practical applications

  • Every STL container and algorithm is a template.
  • Numeric libraries template over float/double precision.
  • Embedded code uses non-type parameters for buffer sizes without heap allocation.

Best practices

  • Keep templates in headers.
  • Give template parameters meaningful names for complex templates.
  • Use concepts (C++20) or static_assert to give clearer errors.

Common mistakes

Template definition only in a .cpp file

Avoid

// stack.hpp: template <class T> class Stack { void push(const T&); };
// stack.cpp: template <class T> void Stack<T>::push(const T&) {}

Prefer

// stack.hpp: define push inside the header

Other files can't instantiate a template whose definition they cannot see; you get undefined-reference link errors.

Mixed-type arguments

Avoid

max_of(3, 7.5);

Prefer

max_of<double>(3, 7.5);

Deduction gives T = int from 3 and T = double from 7.5 — a conflict.

Important notes

  • Template error messages can be long; read the first error and the line in your code that triggered instantiation.
  • C++17 class template argument deduction lets you write std::pair p(1, 2.5); without <int, double>.

Key takeaways

  • Templates generate code per type at compile time.
  • Deduction picks T from arguments; specify it when they conflict.
  • Specialisation customises behaviour for specific types.

Try it yourself

  1. 1
    Write a function template average for a std::vector<T> returning double.
  2. 2
    Write a class template Pair<A, B> with a swap() returning Pair<B, A>.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy are template definitions usually placed in header files?
  • ModerateWhy doesn't `max_of(3, 7.5)` compile for `template <typename T> T max_of(T a, T b);`?
Practise this topic