C++ · Advanced level

Advanced level · Module 1: Templates and Generic Programming · Lesson 2 of 4

Class Templates

Write class templates such as containers and wrappers, and use non-type template parameters.

In this lesson you will

  • Write a class template with member functions
  • Use non-type template parameters and class template argument deduction

Key concepts

class templatemember function definitionsnon-type parameterCTAD

The lesson

Class templates generalise classes: template <typename T> class RingBuffer { … }; holds any element type. Standard containers such as std::vector<T> are class templates.

Non-type template parameters pass values at compile time: template <typename T, std::size_t N> class RingBuffer uses a fixed capacity N known at compile time, so it can use std::array<T, N> internally with no heap allocation.

Since C++17, class template argument deduction (CTAD) lets you write std::pair p{1, 2.5}; and the compiler deduces the template arguments from the constructor.

Step by step

  1. Write RingBuffer<T, N> with push and latest.
  2. Store the elements in std::array<T, N>.
  3. Use it with int readings and std::string messages.
  4. Test wrap-around when more than N items are pushed.

Practice activity

Implement a fixed-size RingBuffer that keeps the last N sensor readings and reports their average.

Expected result: The buffer keeps exactly the last N values and the average updates correctly after wrap-around.

Check your understanding

  1. What is a non-type template parameter?

    Show answer

    A compile-time value, such as a size, passed as a template argument.

  2. What does CTAD do?

    Show answer

    Deduces class template arguments from constructor arguments.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.