Skip to content

Constraints and Concepts (C++20)

In a Nutshell

A mechanism for specifying semantic requirements for template parameters (such as "hashable" or "iterator"), which intercepts incorrect types at compile time and produces readable error messages.

Header File

cpp
<concepts>

Core API Cheat Sheet

OperationSignatureDescription
Concept definitiontemplate <...> concept Name = ...;Defines a named set of constraints
requires expressionrequires { expression; }Checks if an expression is valid
Nested requirementrequires expression;Requires expression validity and result convertible to T
Abbreviated function templatevoid func(C auto& x)Uses concept constraints directly in parameter list
requires clausetemplate<...> requires ...Appends constraints after template declaration
Trailing requiresvoid func(...) requires ...Appends constraints after function parameter list
Logical ANDC1 && C2Combines multiple constraints (conjunction)
Logical ORC1 || C2Combines multiple constraints (disjunction)

Minimal Example

Expand (23 lines)Collapse
cpp
#include <concepts>
#include <vector>
#include <print>

// Define a concept: 'T' must be an integral type
template<typename T>
concept Integral = std::is_integral_v<T>;

// Use concept to constrain function template
// Only accepts types satisfying the Integral concept
auto add(Integral auto a, Integral auto b) {
    return a + b;
}

int main() {
    // OK: int satisfies Integral
    std::println("{}", add(1, 2));

    // Compile Error: double does not satisfy Integral
    // std::println("{}", add(1.0, 2.0));

    return 0;
}

Embedded Applicability: High

  • Pure compile-time feature with zero runtime overhead, suitable for resource-constrained environments.
  • Constraint-driven design intercepts type errors at compile time, avoiding undefined behavior on the target board.
  • Standard library concepts (such as std::integral, std::floating_point) can directly constrain interfaces of hardware register wrapper types.
  • Significantly shortens error messages, accelerating the development and debugging cycle of low-level template libraries.

Compiler Support

GCCClangMSVC
10.010.019.28

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05