← C++

C++ · 13 / 24

Use templates and concepts in practice

Constrain a generic algorithm and verify accepted types at compile time.

  • Large
  • Advanced
  • 90 min

Prerequisites: Headers, CMake and first unit tests, Ownership, lifetime and move semantics

In this tutorial
  1. Define the contract
  2. Separate tools and build
  3. Check observable expectations
  4. Detect an incorrect change
  5. Run the exercise separately
  6. Interpret the verification boundary
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. The valid example compiles and returns the expected value. The negative compilation test passes an unsuitable type and must be rejected. The solution deliberately restricts accepted input to 32-bit types.

Templates let the compiler instantiate code for concrete types. A concept describes which types a contract accepts. It does not replace domain validation of values. This example accepts integers but explicitly excludes bool.

Package contents and individual files

01Define the contract

A concept describes the operations required by a template. The compiler checks these requirements before instantiation. The diagnostic is therefore closer to the interface than an accidental error deep inside the template.

main.cpp · cppOpen file
#include <concepts>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
template <class T>
concept Reading = std::integral<T> && (!std::same_as<T, bool>);
template <Reading T> long long total(const std::vector<T> &values) {
  long long result = 0;
  for (T value : values) {
    if (!std::in_range<long long>(value))
      throw std::overflow_error("Input too large");
    const auto next = static_cast<long long>(value);
    if ((next > 0 && result > std::numeric_limits<long long>::max() - next) ||
        (next < 0 && result < std::numeric_limits<long long>::min() - next))
      throw std::overflow_error("Total too large");
    result += next;
  }
  return result;
}
static_assert(Reading<int>);
static_assert(!Reading<std::string>);
static_assert(!Reading<bool>);
int main() {
  if (total(std::vector<int>{1, 2, 3}) != 6)
    throw std::runtime_error("Wrong total");
  if (total(std::vector<short>{}) != 0)
    throw std::runtime_error("Empty total");
  std::cout << "constraints verified\n";
}

Run / check

python3 verify.py

02Separate tools and build

Put all files in a new folder. Read the compiler options and run verify.py. A failed command must propagate its exit code to the caller.

verify.py · pyOpen file
import subprocess

subprocess.run(["cmake", "-S", ".", "-B", "build"], check=True)
subprocess.run(["cmake", "--build", "build", "--config", "Release"], check=True)
subprocess.run(
    ["ctest", "--test-dir", "build", "-C", "Release", "--output-on-failure"], check=True
)

from pathlib import Path

Path("invalid.cpp").write_text(
    '#define main lesson_main\n#include "main.cpp"\n#undef main\nint main() { total(std::vector<bool>{true}); }\n'
)
invalid = subprocess.run(
    ["g++", "-std=c++20", "-c", "invalid.cpp"], capture_output=True, text=True
)
if invalid.returncode == 0 or "constraints" not in invalid.stderr:
    raise RuntimeError("Expected a concept constraint failure")

03Check observable expectations

The valid example compiles and returns the expected value. The negative compilation test passes an unsuitable type and must be rejected. The solution deliberately restricts accepted input to 32-bit types.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.20)
project(learning LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(lesson main.cpp)
enable_testing()
add_test(NAME behaviour COMMAND lesson)
Expected result

Valid integers are summed. The compiler rejects bool. An excessive value raises overflow_error.

04Detect an incorrect change

Change a checked condition or expected result. Verification must now fail. Restore the original version afterwards. A green process alone does not explain which property is protected.

05Run the exercise separately

Limit input types to at most 32 bits so the example does not promise support for 64-bit input.

06Interpret the verification boundary

The extra condition restricts the accepted types. Extremely long input can still overflow. A general sum contract would also need checked addition and a documented input bound.

Expected result

Verification finishes successfully and checks the conditions named in the example.

Your exercise

Limit input types to at most 32 bits so the example does not promise support for 64-bit input.

Show the solution and explanation

The extra condition restricts the accepted types. Extremely long input can still overflow. A general sum contract would also need checked addition and a documented input bound.

solution.cpp · cppOpen file
#include <concepts>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
template <class T>
concept Reading = std::integral<T> && (!std::same_as<T, bool>);
template <Reading T> long long total(const std::vector<T> &values) {
  long long result = 0;
  for (T value : values)
    result += value;
  return result;
}
static_assert(Reading<int>);
static_assert(!Reading<std::string>);
static_assert(!Reading<bool>);
template <class T>
concept SmallReading = Reading<T> && (sizeof(T) <= 4);
static_assert(SmallReading<int>);
static_assert(!SmallReading<long long>);
int main() {
  if (total(std::vector<int>{1, 2, 3}) != 6)
    throw std::runtime_error("Wrong total");
  if (total(std::vector<short>{}) != 0)
    throw std::runtime_error("Empty total");
  std::cout << "constraints verified\n";
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.