Skip to content

Constraints and Concepts (C++20) ​

In a Nutshell ​

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

Header File ​

#include <concepts>

Core API Cheat Sheet ​

OperationSignatureDescription
Concept definitiontemplate<...> concept Name = constraint-expression;Defines a named set of constraints
requires expressionrequires { /* expression */ }Checks whether the expressions are valid
Nested requirement{ expr } -> std::convertible_to<T>;Requires the expression to be valid and its result convertible to T
Abbreviated template parametervoid f(Concept auto param)Uses a concept constraint directly in the parameter list
requires clausetemplate<typename T> requires Concept<T> void f(T);Appends a constraint after the template declaration
Trailing requirestemplate<typename T> void f(T) requires Concept<T>;Appends a constraint after the function parameter list
Logical ANDConcept1 && Concept2Combines multiple constraints (conjunction)
Logical ORConcept1 || Concept2Combines multiple constraints (disjunction)

Minimal Example ​

C++
#include <concepts>
#include <iostream>

template<typename T>
concept Addable = requires(T a, T b) { a + b; };

template<Addable T>
T add(T a, T b) { return a + b; }

int main() {
    std::cout << add(1, 2) << '\n';     // OK: int satisfies Addable
    // add("a", "b");                   // Error: const char* does not satisfy Addable
}

Embedded Applicability: High ​

  • A pure compile-time feature with zero runtime overhead, well suited to resource-constrained environments
  • Constraint-driven design intercepts type errors at compile time, avoiding undefined behavior triggered on the target board
  • Standard library concepts (such as std::integral, std::same_as) can be used directly to constrain the interfaces of hardware register wrapper types
  • Error messages shrink dramatically, noticeably speeding up the develop-and-debug cycle of low-level template libraries

Compiler Support ​

GCCClangMSVC
10.010.019.28

See Also ​


Some content is referenced from cppreference.com, used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05