Learning Hub Search Ctrl K

Modern C++ › C++20

Concepts and Constraints

Name and check template requirements.

Since C++20 advanced #concepts#requires#constraints#templates#generic-programming

Explanation

A concept is a named, compile-time predicate on template arguments. Used as a constraint, it states what a template requires of its types, and the compiler checks it at the call site, producing short, readable errors instead of pages of instantiation noise. Constraints also take part in overload resolution: a more constrained template wins.

Four ways to apply a constraint:

template <std::integral T> T f(T x);              // constrained type parameter
template <typename T> requires std::integral<T> T g(T x);   // requires-clause
template <typename T> T h(T x) requires std::integral<T>;   // trailing requires
std::integral auto k(std::integral auto x);       // abbreviated function template

Define your own with concept, built from other concepts, type traits and requires-expressions:

template <typename T>
concept Printable = requires(T t, std::ostream& os) {
    { os << t } -> std::same_as<std::ostream&>;   // a compound requirement
};

The standard library provides many in <concepts>: integral, floating_point, same_as, convertible_to, derived_from, copyable, regular, invocable, totally_ordered, and more; <iterator> and <ranges> add iterator and range concepts.

Example

#include <concepts>
#include <iostream>
#include <string>
#include <vector>

template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

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

template <typename T>
concept HasSize = requires(const T& t) {
    { t.size() } -> std::convertible_to<std::size_t>;
};

template <Numeric T>
T twice(T x) { return x * 2; }

void show(Printable auto const& v) { std::cout << v << "\n"; }       // abbreviated syntax

// overloads chosen by constraint
std::string describe(std::integral auto x)       { return "integer " + std::to_string(x); }
std::string describe(std::floating_point auto x) { return "float "   + std::to_string(x); }
std::string describe(const HasSize auto& c)      { return "container of " + std::to_string(c.size()); }

template <typename T>
    requires std::totally_ordered<T>
const T& maxOf(const T& a, const T& b) { return a < b ? b : a; }

struct NoPrint {};

int main() {
    std::cout << twice(21) << " " << twice(1.5) << "\n";
    // twice("x");                                     // error: constraints not satisfied (Numeric)
    show(42); show(std::string("text"));
    // show(NoPrint{});                                // error: NoPrint is not Printable

    std::cout << describe(7) << ", " << describe(2.5) << ", "
              << describe(std::vector<int>{1, 2, 3}) << "\n";
    std::cout << maxOf(3, 9) << " " << maxOf(std::string("a"), std::string("b")) << "\n";
    static_assert(Numeric<int> && !Numeric<std::string>);
    return 0;
}

Common pitfalls

  • A concept checks syntax (that expressions compile), not semantics. std::totally_ordered can’t verify your < is a valid ordering.
  • When two overloads both satisfy their constraints and neither subsumes the other, the call is ambiguous. Build constraints from other concepts with &&/|| so subsumption can work.
  • Concepts can’t be constrained themselves, and can’t recursively refer to themselves.
  • requires requires (T t) { ... } is not a typo: the outer requires is the clause, the inner starts the requires-expression.
  • Hidden constraints: using auto parameters with no concept accepts everything. Prefer a constrained auto.

Legacy vs modern

// C++11/14: SFINAE, errors are cryptic
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
T twice(T x);
// C++20
template <std::integral T> T twice(T x);

C++98 had nothing: the requirements of std::sort (random-access iterators, <) lived only in documentation. See Function Templates and Template Specialization.

Exercises

1. Write a concept Addable that requires a + b to be valid and convertible back to T.
template <typename T>
concept Addable = requires(T a, T b) {
    { a + b } -> std::convertible_to<T>;
};