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
- Write RingBuffer<T, N> with push and latest.
- Store the elements in std::array<T, N>.
- Use it with int readings and std::string messages.
- 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
-
What is a non-type template parameter?
Show answer
A compile-time value, such as a size, passed as a template argument.
-
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.