LearnFrenzy
Sign in Take a free test

Templates and Generic Programming · Lesson 16 of 33

C++20 Concepts

5 min read Updated Nov 7, 2026 Saurabh Samir

A plain template accepts any type, and only fails – with a famously long error message – deep inside its body when the type doesn't support something. Concepts (C++20) let you state up front what a type must support. The compiler checks it at the call site and gives a short, readable error, and the code documents its own requirements.

In this lesson

  • Using standard concepts
  • Three ways to write constraints
  • Writing your own concept with requires
  • Overloading by concept

Standard concepts

#include <concepts>
#include <iostream>

template <std::integral T>                 // only integer types are accepted
T gcd(T a, T b) {
    while (b != 0) { T r = a % b; a = b; b = r; }
    return a;
}

template <std::floating_point T>
T average(T a, T b) { return (a + b) / 2; }

int main() {
    std::cout << gcd(84, 36) << ' ' << gcd(1'000'000'007LL, 13LL) << '\n';
    std::cout << average(2.5, 4.0) << '\n';
    // gcd(2.5, 1.5);    // error: 'double' does not satisfy 'integral' – a one-line message
    return 0;
}

Output

12 1
3.25
Concept (in <concepts>, <iterator>, <ranges>)Satisfied by
std::integral, std::floating_pointinteger / floating-point types
std::same_as<U>, std::convertible_to<U>exactly U / convertible to U
std::totally_ordered, std::equality_comparabletypes with < > etc. / with ==
std::copyable, std::movabletypes that can be copied / moved
std::ranges::range, std::sortablethings you can loop over / iterators you can sort

Three ways to constrain

#include <concepts>
#include <iostream>

template <std::integral T>                         // 1. in the template parameter list
T twice_a(T x) { return 2 * x; }

template <typename T> requires std::integral<T>    // 2. a requires clause
T twice_b(T x) { return 2 * x; }

auto twice_c(std::integral auto x) { return 2 * x; }   // 3. abbreviated: constrained auto parameter

int main() {
    std::cout << twice_a(5) << ' ' << twice_b(6L) << ' ' << twice_c(7) << '\n';
    return 0;
}

Output

10 12 14

Writing your own concept

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

template <typename T>
concept HasArea = requires(const T& shape) {      // what a type must support
    { shape.area() } -> std::convertible_to<double>;
    { shape.name() } -> std::convertible_to<std::string>;
};

struct Square { double side; double area() const { return side * side; } std::string name() const { return "square"; } };
struct Circle { double r; double area() const { return 3.14159 * r * r; } std::string name() const { return "circle"; } };
struct Label  { std::string text; };              // no area(): not a HasArea

template <HasArea S>
void report(const S& s) {
    std::cout << s.name() << " has area " << s.area() << '\n';
}

template <HasArea S>
double total_area(const std::vector<S>& shapes) {
    double t = 0;
    for (const auto& s : shapes) t += s.area();
    return t;
}

int main() {
    report(Square{3});
    report(Circle{1});
    std::cout << total_area(std::vector<Square>{{1}, {2}, {3}}) << '\n';
    static_assert(!HasArea<Label>);               // checked at compile time
    // report(Label{"hi"});                       // error: Label does not satisfy HasArea
    return 0;
}

Output

square has area 9
circle has area 3.14159
14

A concept is a named compile-time predicate. The requires expression lists operations the type must support; nothing is executed – the compiler only checks that the code would compile. Unlike inheritance, the types don't need a common base class: anything with the right members qualifies.

Overloading by concept

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

void show(std::integral auto x)       { std::cout << "integer " << x << '\n'; }
void show(std::floating_point auto x) { std::cout << "real " << x << '\n'; }
void show(const std::string& s)       { std::cout << "text \"" << s << "\"\n"; }

int main() {
    show(42);
    show(3.75);
    show(std::string{"concepts"});
    show('A');                          // char is an integral type
    return 0;
}

Output

integer 42
real 3.75
text "concepts"
integer A

Why concepts matter

They turn template requirements from hidden assumptions into checked documentation, replace the old SFINAE / enable_if tricks with readable code, and shrink error messages from pages to lines. All the C++20 ranges algorithms are constrained with concepts.

Practice

Try it yourself

  1. Write a concept Printable for types that can be written to std::cout, and a function that prints any Printable value in brackets.

    Show solution
    #include <iostream>
    #include <string>
    
    template <typename T>
    concept Printable = requires(std::ostream& os, const T& v) { os << v; };
    
    void bracket(const Printable auto& v) { std::cout << '[' << v << "]\n"; }
    
    int main() {
        bracket(7);
        bracket(std::string{"STL"});
        bracket(2.5);
        return 0;
    }

    Output

    [7]
    [STL]
    [2.5]

Quick check

What problem do concepts solve?

They state and check template requirements up front, giving clear errors and self-documenting code.

Does a requires expression run code?

No – it only checks that the expressions would compile.

Which concept accepts int, long and char?

std::integral.

Summary

  • Concepts constrain templates: std::integral, std::totally_ordered, std::sortable and more.
  • Write them in the template list, a requires clause, or as constrained auto parameters.
  • Define your own with requires expressions; overload functions by concept.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links