C++ · Advanced level

Advanced level · Module 1 of 6 · 22 guided hours

Templates and Generic Programming

Write function and class templates, constrain them with C++20 concepts and design generic algorithms in the style of the standard library.

Learning objectives

  • Write function and class templates
  • Constrain templates with concepts and requires clauses
  • Design generic algorithms that work with iterators and ranges

Topics

  • function templates and deduction
  • class templates
  • non-type template parameters
  • concepts and requires
  • standard concepts
  • iterator-based generic algorithms

Lessons

  1. Lesson 1 Function Templates

    Write functions that work for many types, and understand template argument deduction.

    template <typename T>argument deductioninstantiationheader-only definitions

  2. Lesson 2 Class Templates

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

    class templatemember function definitionsnon-type parameterCTAD

  3. Lesson 3 Concepts and Constraints

    Constrain templates with C++20 concepts so they accept only suitable types and produce clear errors.

    conceptrequires clausestd::integral / std::floating_pointrequires expression

  4. Lesson 4 Generic Algorithms with Iterators and Ranges

    Design algorithms in the standard library's style so they work with any container, and use C++20 ranges.

    iterator categoriesstd::ranges::sortviews::filter / views::transformlazy evaluation

Practical activity

Write a generic statistics library (mean, median, percentile) that works for any numeric container and rejects non-numeric types with a clear concept error.

Expected outcomes

  • Reusable generic code
  • Readable compile-time errors through concepts

Assessment

Practical: implement two constrained templates that pass a provided test file and fail to compile for disallowed types.

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.