Back to Blog

Exploring C++20 Concepts and Constraints

January 5, 2024
10 min read
C++C++20ConceptsTemplates

Exploring C++20 Concepts and Constraints

C++20 introduced concepts, a powerful feature that allows us to specify requirements on template parameters. This makes templates more readable, provides better error messages, and enables more expressive generic code.

What are Concepts?

Concepts are named predicates that constrain template parameters. They specify what operations a type must support.

Defining Concepts

#include <concepts>

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

template<typename T>
concept Printable = requires(T t) {
    std::cout << t;
};

Using Concepts

You can use concepts to constrain template parameters:

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

// Or with requires clause
template<typename T>
requires Addable<T>
T subtract(T a, T b) {
    return a - b;
}

Standard Library Concepts

C++20 provides many standard concepts in <concepts>:

  • std::integral - Integer types
  • std::floating_point - Floating-point types
  • std::copyable - Copy-constructible and copy-assignable
  • std::movable - Move-constructible and move-assignable
  • std::same_as - Types are the same

Benefits

  1. Better Error Messages: Compiler errors are clearer when concepts are violated
  2. Documentation: Concepts serve as self-documenting code
  3. Overloading: Functions can be overloaded based on concept satisfaction
  4. Type Safety: Catch errors at compile-time rather than runtime

Concepts are a game-changer for generic programming in C++!