Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. A concept is a yes/no question about a type
    4. Without a concept: the error comes from inside
    5. Saying what a template needs: requires
    6. Three ways to write the same constraint
    7. Standard concepts you’ll use most
    8. std::same_as: exactly this type
    9. std::ranges::range: anything you can loop over
    10. Writing your own concept
    11. requires expressions: which operations a type must have
    12. Choosing an overload with concepts
    13. Which one should I use?
    14. Under the hood
    15. Common pitfalls
    16. The concept doesn’t check the body
    17. std::integral includes bool and char
    18. Try it yourself

    Module 6 · Generic code

    6.3Concepts

    A concept says what a template needs from its types. Constrain templates with requires and the standard concepts, write your own with a requires expression, and get errors that point at your call instead of deep inside the template.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. A concept is a yes/no question about a type
    4. Without a concept: the error comes from inside
    5. Saying what a template needs: requires
    6. Three ways to write the same constraint
    7. Standard concepts you’ll use most
    8. std::same_as: exactly this type
    9. std::ranges::range: anything you can loop over
    10. Writing your own concept
    11. requires expressions: which operations a type must have
    12. Choosing an overload with concepts
    13. Which one should I use?
    14. Under the hood
    15. Common pitfalls
    16. The concept doesn’t check the body
    17. std::integral includes bool and char
    18. Try it yourself

    Key terms

    constraint
    A condition a template puts on its types, checked while compiling. A call whose types don't meet it is rejected at the call.
    concept
    A named constraint: a test on a type that is true or false while compiling, like std::integral<int>. The standard ones are in <concepts>; you define your own with the keyword concept.
    satisfied
    A constraint is satisfied when it's true for the types in a call.
    requires clause
    requires and a condition, written after template <…>. The template can only be used with types that satisfy it.
    type constraint (template <std::integral T>)
    A concept written in place of typename in the template header. Short for a requires clause on that one type.
    constrained auto
    std::integral auto x: a parameter or variable whose deduced type must satisfy the concept.
    requires expression
    requires(parameters) { … }: true if every expression listed inside would compile. The usual way to say which operations a type must have.
    compound requirement
    { expression } -> Concept<…>; inside a requires expression: the expression must compile, and its type must satisfy the concept.

    A template from Function templates accepts any type. If you call it with a type that doesn’t fit, the compiler only finds out while generating the template’s body, and the error points inside the template, not at your call. A concept writes down what the template needs, so the compiler checks your call against that list first and tells you which requirement failed.

    In 30 seconds

    • A concept is a yes/no test on a type, answered while compiling: std::integral<int> is true, std::integral<double> is false.
    • Add requires std::integral<T> after template <typename T>, and calls with other types are rejected at the call, with a message that names the requirement they failed.
    • std::integral auto n is the short form for a parameter that must satisfy a concept.
    • Write your own with concept, and list the operations a type must have in a requires expression.

    A concept is a yes/no question about a type

    The standard concepts live in <concepts>. Each one takes a type in angle brackets and gives true or false, worked out while compiling, so you can print it or check it with static_assert:

    #include <concepts>
    #include <print>
    #include <string>
    
    std::println("{}", std::integral<int>);
    std::println("{}", std::integral<double>);
    std::println("{}", std::floating_point<double>);
    std::println("{}", std::integral<std::string>);
    static_assert(std::integral<long>);

    Output

    true
    false
    true
    false

    On its own that’s a type check. The value of a concept is in putting it on a template.

    Without a concept: the error comes from inside

    This template doubles a number. Nothing in its declaration says it needs a number, so the compiler accepts the call with a std::string, starts generating twice for std::string, and only fails at x * 2:

    #include <print>
    #include <string>
    
    template <typename T>
    T twice(T x) {
        return x * 2;
    }
    
    int main() {
        std::println("{}", twice(21));
        std::println("{}", twice(std::string{"GA"}));
    }

    The compiler rejects this

    main.cpp: In instantiation of ‘T twice(T) [with T = std::__cxx11::basic_string<char>]’:
    main.cpp:11:29:   required from here
       11 |     std::println("{}", twice(std::string{"GA"}));
          |                        ~~~~~^~~~~~~~~~~~~~~~~~~
    main.cpp:6:14: error: no match for ‘operator*’ (operand types are ‘std::__cxx11::basic_string<char>’ and ‘int’)
        6 |     return x * 2;
          |            ~~^~~

    The error is reported at x * 2, inside twice; your call shows up only as the place the template was “required from”. In a real library, the failing line can be several files and dozens of templates away from your code, and the message grows with every template in between.

    Saying what a template needs: requires

    A requires clause goes between the template header and the function. Here it says T must be a whole number or a floating-point number. || and && combine concepts the same way they combine bool values:

    #include <concepts>
    #include <print>
    
    template <typename T>
        requires std::integral<T> || std::floating_point<T>
    T twice(T x) {
        return x * 2;
    }
    
    int main() {
        std::println("{}", twice(21));
        std::println("{}", twice(1.25));
    }

    Output

    42
    2.5

    Now make the same mistake. The compiler checks the constraint before it looks at the body, so it never generates the broken twice<std::string>. The error is at your call, and it says which part of the constraint wasn’t met:

    #include <concepts>
    #include <print>
    #include <string>
    
    template <typename T>
        requires std::integral<T> || std::floating_point<T>
    T twice(T x) {
        return x * 2;
    }
    
    int main() {
        std::println("{}", twice(std::string{"GA"}));
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:12:29: error: no matching function for call to ‘twice(std::string)’
       12 |     std::println("{}", twice(std::string{"GA"}));
          |                        ~~~~~^~~~~~~~~~~~~~~~~~~
    main.cpp:12:29: note: there is 1 candidate
    main.cpp:7:3: note: candidate 1: ‘template<class T>  requires (integral<T>) || (floating_point<T>) T twice(T)’
        7 | T twice(T x) {
          |   ^~~~~
    main.cpp:7:3: note: template argument deduction/substitution failed:
    main.cpp:7:3: note: constraints not satisfied
    main.cpp: In substitution of ‘template<class T>  requires (integral<T>) || (floating_point<T>) T twice(T) [with T = std::__cxx11::basic_string<char>]’:
    main.cpp:12:29:   required from here
       12 |     std::println("{}", twice(std::string{"GA"}));
          |                        ~~~~~^~~~~~~~~~~~~~~~~~~
    main.cpp:7:3:   required by the constraints of ‘template<class T>  requires (integral<T>) || (floating_point<T>) T twice(T)’
    main.cpp:6:31: note: no operand of the disjunction is satisfied
        6 |     requires std::integral<T> || std::floating_point<T>
          |              ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
    cc1plus: note: set ‘-fconcepts-diagnostics-depth=’ to at least 2 for more detail

    Read it from the top: no matching function for your call, the one candidate, “constraints not satisfied”, and finally the line of the requires clause with “no operand of the disjunction is satisfied”, which means neither side of the || was true.

    Key ideaA constraint is part of the function's signature

    A template whose constraint isn’t satisfied is treated as if it didn’t exist for that call. So the message is “no matching function”, followed by the constraint that ruled it out, rather than an error from somewhere inside the template.

    Three ways to write the same constraint

    The requires clause works for any condition. When the condition is a single concept on one type, there are two shorter spellings. These three functions accept exactly the same types:

    #include <concepts>
    #include <print>
    
    template <typename T>
        requires std::integral<T>
    bool is_even_a(T n) {
        return n % 2 == 0;
    }
    
    template <std::integral T>
    bool is_even_b(T n) {
        return n % 2 == 0;
    }
    
    bool is_even_c(std::integral auto n) {
        return n % 2 == 0;
    }
    
    int main() {
        std::println("{} {} {}", is_even_a(4), is_even_b(7), is_even_c(10L));
    }

    Output

    true false true
    • template <std::integral T> puts the concept where typename was. It’s called a type constraint.
    • std::integral auto n is constrained auto: the abbreviated template from Function templates, with a concept in front of auto. The type deduced for n must satisfy std::integral.

    Constrained auto also works for variables. It doesn’t change what auto deduces; it checks it:

    #include <concepts>
    #include <print>
    #include <string>
    
    std::string dna = "GATTACA";
    std::integral auto length = dna.size();
    std::floating_point auto gc = 2.0 / 7.0;
    std::println("{} {:.2f}", length, gc);

    Output

    7 0.29

    If dna.size() ever returned something that isn’t a whole number, this line would stop compiling instead of quietly working with a different type.

    Standard concepts you’ll use most

    ConceptTrue when
    std::integral<T>T is a whole-number type, including char and bool
    std::floating_point<T>T is float, double or long double
    std::same_as<T, U>T and U are exactly the same type
    std::convertible_to<From, To>a From converts to a To without a cast
    std::ranges::range<T>a T has a begin() and an end(), so you can loop over it with a range-based for (from <ranges>)

    std::same_as: exactly this type

    With constrained auto, the deduced type goes in as the concept’s first argument. So std::same_as<bool> auto on means “on’s type T, where std::same_as<T, bool> is true”. A plain bool parameter would accept 1 and convert it; this one accepts only a real bool, so set_verbose(1) doesn’t compile:

    #include <concepts>
    #include <print>
    
    void set_verbose(std::same_as<bool> auto on) {
        std::println("verbose: {}", on);
    }
    
    int main() {
        set_verbose(1);
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:9:16: error: no matching function for call to ‘set_verbose(int)’
        9 |     set_verbose(1);
          |     ~~~~~~~~~~~^~~
    main.cpp:9:16: note: there is 1 candidate
    main.cpp:4:6: note: candidate 1: ‘template<class auto:11>  requires  same_as<auto:11, bool> void set_verbose(auto:11)’
        4 | void set_verbose(std::same_as<bool> auto on) {
          |      ^~~~~~~~~~~
    main.cpp:4:6: note: template argument deduction/substitution failed:
    main.cpp:4:6: note: constraints not satisfied
    In file included from main.cpp:1:
    /usr/include/c++/15/concepts: In substitution of ‘template<class auto:11>  requires  same_as<auto:11, bool> void set_verbose(auto:11) [with auto:11 = int]’:
    main.cpp:9:16:   required from here
        9 |     set_verbose(1);
          |     ~~~~~~~~~~~^~~
    /usr/include/c++/15/concepts:59:15:   required for the satisfaction of ‘__same_as<_Tp, _Up>’ [with _Tp = int; _Up = bool]
    /usr/include/c++/15/concepts:64:13:   required for the satisfaction of ‘same_as<auto:11, bool>’ [with auto:11 = int]
    /usr/include/c++/15/concepts:59:32: note: the expression ‘is_same_v<_Tp, _Up> [with _Tp = int; _Up = bool]’ evaluated to ‘false’
          |       concept __same_as = std::is_same_v<_Tp, _Up>;
          |                           ~~~~~^~~~~~~~~~~~~~~~~~~

    The fix is at the call: write set_verbose(true), which also tells the reader what the argument means.

    std::ranges::range: anything you can loop over

    print_all works with every container from Module 3, and with your own types that have begin() and end(). An int isn’t a range, so print_all(5) wouldn’t compile:

    #include <array>
    #include <print>
    #include <ranges>
    #include <string>
    #include <vector>
    
    void print_all(const std::ranges::range auto& items) {
        for (const auto& item : items) {
            std::print("{} ", item);
        }
        std::println("");
    }
    
    int main() {
        print_all(std::vector<int>{3, 1, 4});
        print_all(std::array<double, 2>{0.5, 1.5});
        print_all(std::string{"GATC"});
        std::println("{}", std::ranges::range<int>);
    }

    Output

    3 1 4
    0.5 1.5
    G A T C
    false

    const std::ranges::range auto& reads as: a const reference to some type that satisfies std::ranges::range. The parameter is still a reference, so nothing is copied.

    Writing your own concept

    When the same condition appears in several places, give it a name. A concept definition is template <typename T>, the keyword concept, a name, = and a condition that’s true or false while compiling:

    #include <concepts>
    #include <print>
    #include <string>
    
    template <typename T>
    concept Number = std::integral<T> || std::floating_point<T>;
    
    double average(Number auto a, Number auto b) {
        return (a + b) / 2.0;
    }
    
    int main() {
        static_assert(Number<float>);
        static_assert(!Number<std::string>);
        std::println("{}", average(3, 4));
        std::println("{}", average(2, 0.5));
    }

    Output

    3.5
    1.25

    Each Number auto deduces its own type, so average(2, 0.5) takes an int and a double. Use template <Number T> with T a, T b when both must be the same type.

    requires expressions: which operations a type must have

    Often a template doesn’t care what a type is, only what you can do with it. A requires expression lists those operations. requires(const T& c) { … } introduces a pretend parameter c to write the expressions with; nothing is ever called. The result is true if every line inside would compile:

    #include <concepts>
    #include <cstddef>
    #include <print>
    #include <string>
    #include <vector>
    
    template <typename T>
    concept HasSize = requires(const T& c) {
        { c.size() } -> std::convertible_to<std::size_t>;
    };
    
    struct Read {
        std::string bases;
        std::size_t size() const { return bases.size(); }
    };
    
    void report(const HasSize auto& item) {
        std::println("{} long", item.size());
    }
    
    int main() {
        report(std::string{"GATTACA"});
        report(std::vector<int>{1, 2, 3});
        report(Read{"ACGT"});
        std::println("{}", HasSize<int>);
    }

    Output

    7 long
    3 long
    4 long
    false

    The line inside is a compound requirement: { c.size() } must compile, and -> std::convertible_to<std::size_t> says its result must convert to std::size_t. The result’s type goes in as the concept’s first argument, as with constrained auto. To require only that an expression compiles, write it on its own: c.size();.

    Read never says it satisfies HasSize. It has a size() member function (Structs and classes covers those) that returns a std::size_t, and that’s enough.

    Choosing an overload with concepts

    Concepts also pick between overloads. The compiler drops every candidate whose constraint isn’t satisfied, then chooses among the rest:

    #include <concepts>
    #include <print>
    
    void describe(std::integral auto n) {
        std::println("whole number: {}", n);
    }
    
    void describe(std::floating_point auto x) {
        std::println("decimal: {}", x);
    }
    
    int main() {
        describe(42);
        describe(0.75);
    }

    Output

    whole number: 42
    decimal: 0.75

    Without the concepts, the two declarations would be the same template defined twice, and the program wouldn’t compile.

    Which one should I use?

    WhatWhenWhyHow
    Constrained autoEach parameter’s type stands on its own, and you don’t need to name it.The shortest form; the parameter list says what it accepts.void f(std::integral auto n)
    Type constraintYou need the type’s name, or two parameters must have the same type.Names T once and constrains it in the same place.template <std::integral T> T gcd(T a, T b)
    requires clauseThe condition combines concepts with && or ||, or involves several types.Takes any condition.requires std::integral<T> || std::floating_point<T>
    Your own conceptThe same condition is used in several places, or you need to check for operations.The name documents the intent and appears in error messages.template <typename T> concept HasSize = requires(…) { … };

    Rule of thumb: constrain every template you write. Reach for a standard concept first, and write your own when you find yourself repeating the same condition.

    Under the hood

    A concept is checked only while compiling. It produces no code, and for the same types, a constrained template generates the same machine code as it would without the constraint. A concept’s result is an ordinary compile-time bool: it can go in a static_assert, as the first example showed, or initialize a constexpr variable.

    When you call a constrained template, the compiler works in this order:

    1. It deduces T from your arguments, as in Function templates.
    2. It checks the constraint with that T. If it isn’t satisfied, the template is dropped from the list of candidates. That’s not an error yet: another overload might fit.
    3. If no candidate is left, it reports “no matching function”, with a note naming the constraint that failed.
    4. Only for the chosen candidate does it generate the body.

    Because step 2 comes before step 4, the error is about your call. The broken body is never generated, so there’s nothing inside it to complain about, however deep the template goes.

    Modern C++Concepts are C++20

    Before C++20, libraries limited templates with tricks built on std::enable_if. You’ll see it in older code; it does the same job with much harder-to-read declarations and errors. In new code, use concepts.

    Common pitfalls

    The concept doesn’t check the body

    A concept checks the call, not the template body. If the body uses an operation the concept doesn’t list, a type can satisfy the concept and still fail inside the template, with the old kind of error:

    #include <concepts>
    #include <cstddef>
    #include <print>
    #include <string>
    
    template <typename T>
    concept HasSize = requires(const T& c) {
        { c.size() } -> std::convertible_to<std::size_t>;
    };
    
    struct Read {
        std::string bases;
        std::size_t size() const { return bases.size(); }
    };
    
    void show(const HasSize auto& item) {
        std::println("{} long, starts {}", item.size(), item.front());
    }
    
    int main() {
        show(Read{"ACGT"});
    }

    The compiler rejects this

    main.cpp: In instantiation of ‘void show(const auto:11&) [with auto:11 = Read]’:
    main.cpp:21:9:   required from here
       21 |     show(Read{"ACGT"});
          |     ~~~~^~~~~~~~~~~~~~
    main.cpp:17:58: error: ‘const struct Read’ has no member named ‘front’
       17 |     std::println("{} long, starts {}", item.size(), item.front());
          |                                                     ~~~~~^~~~~

    The fix is to list everything the body uses: add c.front(); to the concept (and then Read is rejected at the call), or give Read a front() member function.

    std::integral includes bool and char

    bool and char are integer types in C++, so std::integral accepts them. That’s rarely what a number function wants:

    #include <concepts>
    #include <print>
    
    bool is_even(std::integral auto n) {
        return n % 2 == 0;
    }
    
    int main() {
        std::println("{} {}", is_even(true), is_even('A'));
    }

    Output

    false false

    Write a concept that leaves them out. Here Integer rejects bool; add && !std::same_as<T, char> to reject char too:

    #include <concepts>
    #include <print>
    
    template <typename T>
    concept Integer = std::integral<T> && !std::same_as<T, bool>;
    
    bool is_even(Integer auto n) {
        return n % 2 == 0;
    }
    
    int main() {
        std::println("{}", is_even(true));
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:12:31: error: no matching function for call to ‘is_even(bool)’
       12 |     std::println("{}", is_even(true));
          |                        ~~~~~~~^~~~~~
    main.cpp:12:31: note: there is 1 candidate
    main.cpp:7:6: note: candidate 1: ‘template<class auto:11>  requires  Integer<auto:11> bool is_even(auto:11)’
        7 | bool is_even(Integer auto n) {
          |      ^~~~~~~
    main.cpp:7:6: note: template argument deduction/substitution failed:
    main.cpp:7:6: note: constraints not satisfied
    main.cpp: In substitution of ‘template<class auto:11>  requires  Integer<auto:11> bool is_even(auto:11) [with auto:11 = bool]’:
    main.cpp:12:31:   required from here
       12 |     std::println("{}", is_even(true));
          |                        ~~~~~~~^~~~~~
    main.cpp:5:9:   required for the satisfaction of ‘Integer<auto:11>’ [with auto:11 = bool]
    main.cpp:5:39: note: the expression ‘!(same_as<T, bool>) [with T = bool]’ evaluated to ‘false’
        5 | concept Integer = std::integral<T> && !std::same_as<T, bool>;
          |                                       ^~~~~~~~~~~~~~~~~~~~~~

    Try it yourself

    Try it yourself

    count_gc works with any type that has size() and [], but its first line doesn’t say so. Write a concept Sequence with a requires expression that needs seq.size() (converting to std::size_t) and seq[i] (converting to char), and use it to constrain count_gc. Add static_assert(!Sequence<int>); to main to check it.

    #include <cstddef>
    #include <print>
    #include <string>
    #include <vector>
    
    template <typename T>
    std::size_t count_gc(const T& seq) {
        std::size_t n = 0;
        for (std::size_t i = 0; i < seq.size(); ++i) {
            if (seq[i] == 'G' || seq[i] == 'C') {
                ++n;
            }
        }
        return n;
    }
    
    int main() {
        std::string dna = "GATTACA";
        std::vector<char> letters = {'G', 'C', 'C', 'A'};
        std::println("{} {}", count_gc(dna), count_gc(letters));
    }

    Expected output

    2 3
    Show a hint

    Inside the requires expression, give yourself two pretend parameters, const T& seq and std::size_t i. Then write one compound requirement for seq.size() and one for seq[i].

    Show a solution
    #include <concepts>
    #include <cstddef>
    #include <print>
    #include <string>
    #include <vector>
    
    template <typename T>
    concept Sequence = requires(const T& seq, std::size_t i) {
        { seq.size() } -> std::convertible_to<std::size_t>;
        { seq[i] } -> std::convertible_to<char>;
    };
    
    std::size_t count_gc(const Sequence auto& seq) {
        std::size_t n = 0;
        for (std::size_t i = 0; i < seq.size(); ++i) {
            if (seq[i] == 'G' || seq[i] == 'C') {
                ++n;
            }
        }
        return n;
    }
    
    int main() {
        static_assert(!Sequence<int>);
        std::string dna = "GATTACA";
        std::vector<char> letters = {'G', 'C', 'C', 'A'};
        std::println("{} {}", count_gc(dna), count_gc(letters));
    }

    Sequence lists exactly the two operations count_gc uses, so any type that passes the check also compiles inside the body. std::string and std::vector<char> both have size() and [], so the calls still work, and int is rejected with a constraints-not-satisfied error at the call instead of an error inside count_gc.

    Saved in this browser only.