Site Tools


cpp-concepts

Table of Contents

C++ Concepts

Concepts (C++20) are compile-time predicates that check whether a type satisfies a set of requirements (methods, types, operations). They replace ad-hoc SFINAE and enable_if, providing clearer, more readable template constraints. A template with a requires clause only participates in overload resolution if the concept is satisfied.

Use concepts in C++20+ to write more readable and maintainable generic code with clear type requirements.

Example

This example shows concepts defining and checking type requirements.

// compile: g++ -std=c++20 -o concepts concepts.cpp
// run: ./concepts
// description: concepts enforce template requirements at compile time
 
#include <iostream>
#include <concepts>
#include <vector>
 
// Define a concept: Drawable types must have a draw method
template <typename T>
concept Drawable = requires(T t) {
    t.draw();
};
 
class Circle {
public:
    void draw() { std::cout << "Drawing circle\n"; }
};
 
class Rectangle {
public:
    void draw() { std::cout << "Drawing rectangle\n"; }
};
 
// Function template constrained by concept
template <Drawable T>
void render(T& shape) {
    shape.draw();
}
 
int main() {
    Circle c;
    Rectangle r;
 
    render(c);  // OK: Circle satisfies Drawable
    render(r);  // OK: Rectangle satisfies Drawable
 
    return 0;
}
cpp-concepts.md · Last modified: by 127.0.0.1