bhylu.com

Advertisements

C++ Concepts

Use a C++20 concept so a count operation accepts integral values rather than every type with accidental conversions.

How it works

A concept describes compile-time requirements on template arguments. Constraints improve an interface by rejecting unsuitable types near the call instead of allowing a distant implementation error. They do not prove every semantic property: an integral type still has finite range and a container still needs valid lifetimes. Use a concept to express the minimum meaningful operations and domain, not to promise runtime validation that it cannot perform. This small helper deliberately excludes bool because truth values are not parcel counts.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror concepts.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · concepts.cpp

#include <iostream>
#include <concepts>
#include <type_traits>

template<class T>
concept Count = std::integral<T> && (!std::same_as<T, bool>);

template<Count T>
T twice(T value) { return value + value; }

int main() {
    std::cout << "Doubled: " << twice(6) << '\n';
}

Expected result

Doubled: 12

The fixed value is representable after doubling. A call with a string or bool does not satisfy Count; it is intentionally not part of the runnable listing. A general public doubling function would still check arithmetic bounds or choose an explicit modular contract. Constraints describe valid types, while checks and domain types describe valid values.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.