Learn C++
#include "templates/concepts.hpp"

Concepts (C++20)

//concept

Concepts name requirements on template arguments: template <std::integral T> constrains T to integer-like types, replacing pages of enable_if gymnastics with a readable bound. Violations fail with a clear message naming the unsatisfied concept instead of a novel-length substitution backtrace.

The standard library ships ready-made concepts (integral, floating_point, same_as, convertible_to, ranges...), and requires-clauses express compound conditions (requires std::integral<T> && sizeof(T) > 1). Concepts don't change what compiles — they change how loudly and clearly misuse fails.

//how it works
1

Constrain with a name

template <std::integral T> T twice(T x) accepts ints and longs but rejects strings and doubles at the call site.

2

Clear errors

A violated concept reports which requirement failed — versus pages of substitution-failure context without it.

3

Compose with requires

requires std::integral<T> && (sizeof(T) >= 4) stacks conditions; custom concept definitions name reusable bundles.

4

Constrain, don't SFINAE

New code should reach for concepts first — enable_if remains only for pre-C++20 compatibility.

//example
#include <iostream>
#include <concepts>
 
template <std::integral T>
T double_it(T x) { return x * 2; }
 
int main() {
std::cout << double_it(21) << std::endl;
return 0;
}
Output
42
1double_it(21) checks int against std::integral — satisfied, so instantiation proceeds.
2A call like double_it(2.5) would fail immediately with a message naming the integral requirement.
342 prints — constrained genericity with readable diagnostics.
//use cases
Bounding numeric templates to integral or floating_point families
Replacing enable_if mazes with self-documenting constraints
Overloading on concepts (integral vs floating_point versions) cleanly
Range-based APIs constrained to std::ranges::range inputs

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.