TRT
Sign in

Advanced · Module 9

Templates, Concepts and Compile-Time Code

Write one function or container that works for every type, constrain it with concepts, and compute at compile time.

Start the modulePro7 lessons · about 75 minutes

Templates are the reason std::vector<int> and std::vector<std::string> share one implementation. This module builds from function and class templates through specialization, concepts, compile-time evaluation and parameter packs. Its final project applies those tools to a reusable result type, while each lesson explains what the compiler checks and when it generates code.

  1. 1Function Templates: One max for Every TypePro — members onlyWrite a single max that works for ints, strings and your own types, and read the deduction and instantiation rules that make it safe.10 min
  2. 2Class Templates: A Generic Pair and ContainerPro — members onlyTurn the Pair sketch from the example into a full class template, separate interface from implementation, and predict per-type instantiation.10 min
  3. 3Specialization: Customizing for One TypePro — members onlyKeep one generic print for all types, specialize it for string literals and std::string, and fix the missing include that blocks compilation.9 min
  4. 4Concepts and Constraints: Requirements That Read Like EnglishPro — members onlyReplace fifty-line template errors with a named C++20 concept, constrain max_of and Pair with requires clauses, and read diagnostics in one line.11 min
  5. 5Project: A Generic Result Type for the LibraryPro — members onlyBuild a constrained Result for catalogue lookups that carries either a value or an error, composes without exceptions, and reports misuse at compile time.12 min
  6. 6Compile-Time Programming: constexpr, consteval and static_assertPro — members onlyMove pure work and validation into compilation with constexpr functions, immediate functions and compile-time assertions.11 min
  7. 7Variadic Templates and Perfect ForwardingPro — members onlyAccept any number of typed arguments, preserve their value categories, and build generic factories without accidental copies.12 min