C++20 Concepts — Why std::list Fails Your Range Constraint
Requires expressions check constraints in order—subscript operators reject std::list before return-type checks run.
20+ years shipping performance-critical C and C++ systems. Drawn from code that ran under real load.
- ✓Deep production experience
- ✓Understanding of internals and trade-offs
- ✓Experience debugging complex systems
- Concepts are compile-time predicates that constrain template parameters — checked before instantiation, not during
- A concept definition uses a requires expression to list required operations and return types
- The four syntax forms (terse, requires clause, trailing requires, constrained auto) are semantically identical but differ in readability
- Subsumption ranks overloads automatically when concepts reference each other by name — inline requires does not subsume
- Performance is zero runtime cost; compile times can increase in constraint-heavy translation units
C++20 Concepts are a compile-time predicate system that lets you specify and enforce type requirements on templates as part of the language, not as documentation. Before Concepts, template constraints were expressed through SFINAE (Substitution Failure Is Not An Error) tricks—std::enable_if, decltype expressions, and trait-based static_asserts—which were verbose, error-prone, and produced inscrutable error messages.
Concepts solve this by giving you a first-class way to say "this template parameter must support these operations" and having the compiler enforce it at the point of use, with clear diagnostics. For example, std::sort requires random-access iterators; with Concepts, you can write template<std::random_access_iterator Iter> and the compiler will reject std::list at the call site with a message like "constraint not satisfied: std::random_access_iterator<std::_List_iterator<int>>" instead of a 200-line template instantiation backtrace.
Under the hood, a concept is a constexpr bool expression that the compiler evaluates at compile time. It's defined with the concept keyword and typically combines type traits (like std::is_integral_v) and requires expressions that check for valid syntax (e.g., { a + b } -> std::convertible_to<int>).
The requires clause can appear in four places: as a template parameter constraint (template<typename T> requires C<T>), as a trailing requires clause on a function template, as a constrained auto parameter in abbreviated function templates (void f(std::integral auto x)), and as a constraint on class template specializations. Each has different use cases: constrained template parameters are best for most generic code, trailing requires clauses allow fine-grained control over overload resolution, and abbreviated templates reduce boilerplate for simple cases.
Concepts participate in overload resolution through subsumption—a partial ordering where more constrained templates are preferred over less constrained ones. This is not just syntactic; the compiler understands that std::random_access_iterator implies std::forward_iterator, so a function constrained on the former will be chosen over one constrained on the latter when both match.
This replaces the old SFINAE-based overload selection with a principled, composable system. In production, you'll use Concepts to replace std::enable_if in class templates (e.g., template<typename T> requires std::is_arithmetic_v<T> class Matrix), to constrain lambdas (auto lambda = []<std::integral T>(T x) { ... }), and to migrate legacy SFINAE code to something maintainable.
The key gotchas: concepts are not evaluated lazily (they can cause hard errors if you use them with incomplete types), subsumption only works with atomic constraints (not conjunctions of traits), and you must avoid circular dependencies in requires expressions. When designing custom concepts, prefer composition of standard concepts over reinventing checks, and always test with both satisfying and non-satisfying types to ensure your error messages are helpful.
Imagine you're running a bakery and you hire helpers. You don't just want 'anyone' — you want someone who can frost cakes AND use an oven. Instead of hiring them and discovering mid-shift they can't bake, you check those skills upfront at the interview. C++20 Concepts work exactly like that job interview checklist for your template functions: you state exactly what abilities a type must have before the compiler even attempts to compile your code. No more cryptic 30-line error messages — just a clean 'this type doesn't meet the requirements' message at the right moment.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
Before C++20, writing generic code in C++ was like signing a contract written in invisible ink. You'd author a template, ship it, and only discover at compile time — buried under an avalanche of substitution-failure errors — that a user passed a type that simply wasn't compatible. The template machinery would choke deep inside instantiation, producing error messages that looked like the compiler had a breakdown. Senior engineers learned to read those stack traces like tea leaves. Everyone else just suffered.
Concepts are C++20's answer to that chaos. They let you attach formal, human-readable constraints to templates. The compiler checks those constraints before even attempting instantiation. If a type doesn't satisfy a concept, you get a crisp, targeted diagnostic pointing directly at the mismatch. Beyond error messages, concepts enable overload resolution that was previously impossible without arcane SFINAE tricks — letting you write genuinely different code paths based on what a type can do, not just what it is.
By the end of this article you'll be able to define your own named concepts, apply them using all four syntax forms, understand how concept subsumption drives overload selection, spot the subtle gotchas that bite even experienced engineers, and know exactly when reaching for a concept adds value versus when it's overkill. We'll look at real output, real diagnostics, and the performance implications that matter in production.
Why C++20 Concepts Are a Compile-Time Contract, Not a Documentation Comment
C++20 concepts are a language mechanism that lets you specify and enforce type requirements at compile time. Instead of relying on template instantiation failures that produce hundreds of lines of error spew, you define a predicate over template arguments — a boolean expression evaluated by the compiler — that must hold before the template is even considered. The core mechanic is the requires clause, which can check for the existence of member functions, valid expressions, or nested type aliases.
In practice, a concept acts as a gatekeeper. If a type doesn't satisfy the concept, the compiler rejects the call with a single, clear error message pointing to the violated constraint — not a cascade of substitution failures deep inside the template body. For example, std::list fails std::ranges::sort because it lacks random-access iterators; the concept std::ranges::random_access_range catches this at the call site, not after pages of failed instantiations. Concepts compose: you can build Sortable from RandomAccessRange and Comparable, and the compiler checks each piece independently.
Use concepts when you want to express interface contracts that are checked early, produce readable errors, and enable overloading based on type capabilities. In real systems, this means you can write a single algorithm that dispatches to different implementations based on iterator category — without SFINAE hacks or tag dispatch. The payoff is faster compilation (fewer failed instantiations) and code that documents its own requirements. If you're writing a template that expects more than just a type name, you should be using a concept.
static_assert or runtime validation — it constrains which types are accepted, not what values they hold.std::list passed to a std::ranges::sort-like algorithm compiles but runs O(n²) instead of O(n log n) because the concept was too loose (e.g., input_range instead of random_access_range).random_access_range for sorting, forward_range for single-pass transforms — and test with a container that should fail.std::list passes input_range but fails random_access_range, which is the difference between correct and silently slow code.Defining Concepts: What a Constraint Actually Is Under the Hood
A concept is a named predicate — a compile-time boolean expression evaluated against one or more template parameters. Syntactically it looks like a variable template that yields true or false, but semantically it's much richer because the compiler uses concepts for constraint checking, overload ranking, and diagnostics, none of which an ordinary bool variable template can do.
The body of a concept is a constraint expression. The most powerful form uses a requires expression — a block that lists operations the type must support, return types those operations must yield, and nested requirements that must hold. The requires expression doesn't execute any code; it checks whether the expression would be well-formed. This is the critical distinction: it's purely a syntactic and semantic check at the point of constraint evaluation.
Under the hood the compiler normalises every constraint into a conjunction or disjunction of atomic constraints. An atomic constraint is an expression that can't be decomposed further — typically a single requires expression or a concept specialisation. This normalisation is what powers subsumption: the compiler can determine that one concept is strictly more refined than another, enabling it to pick the 'most constrained' overload without ambiguity.
A concept cannot be recursive, cannot refer to itself, and cannot be specialised. These restrictions aren't arbitrary — they keep constraint normalisation decidable and prevent infinite loops during compilation.
#include <concepts> #include <iostream> #include <string> #include <vector> // --- Defining a simple concept using a requires expression --- // The requires expression checks that: // 1. T has a .size() member returning something convertible to std::size_t // 2. T supports the subscript operator [] with an integral index // 3. T is default-constructible template <typename T> concept Sequence = requires(T container, std::size_t index) { { container.size() } -> std::convertible_to<std::size_t>; // return-type constraint { container[index] }; // simple validity check T{}; // nested requirement: must default-construct }; // --- A more refined concept that builds ON Sequence --- // Because SortableSequence requires Sequence AND ordering, it SUBSUMES Sequence. // The compiler will prefer SortableSequence overloads over plain Sequence overloads. template <typename T> concept SortableSequence = Sequence<T> && requires(T container, std::size_t i) { { container[i] < container[i] } -> std::same_as<bool>; // elements must be comparable }; // --- Function constrained with the plain Sequence concept --- // This overload is chosen for types satisfying Sequence but NOT SortableSequence. template <Sequence S> void describe(const S& container) { std::cout << "[Sequence] size = " << container.size() << '\n'; } // --- More-constrained overload: chosen when SortableSequence is satisfied --- // Subsumption guarantees no ambiguity — the compiler picks this one for std::vector<int>. template <SortableSequence S> void describe(const S& container) { std::cout << "[SortableSequence] size = " << container.size() << ", first element = " << container[0] << '\n'; } int main() { std::vector<int> numbers = {42, 7, 19}; describe(numbers); // SortableSequence overload wins — int supports operator< // std::string satisfies Sequence (has size(), operator[]) AND SortableSequence // because char supports operator< std::string greeting = "hello"; describe(greeting); // Static assertion: document assumptions directly in code static_assert(Sequence<std::vector<int>>, "vector<int> must satisfy Sequence"); static_assert(SortableSequence<std::vector<int>>, "vector<int> must satisfy SortableSequence"); return 0; }
container.size() } -> std::convertible_to<std::size_t> does NOT call size(). It asks: 'would this expression compile and would its type satisfy convertible_to?' That's why concepts have zero runtime cost.Four Ways to Apply Concepts — and When to Use Each One
C++20 gives you four distinct syntactic positions to attach a concept. They're all equivalent in terms of what constraint they impose, but they differ dramatically in readability, and choosing the right form is a genuine engineering decision.
The terse template syntax — writing the concept name directly where typename would go — is the cleanest for single-parameter constraints. It communicates intent at a glance. Use it when a function takes one constrained type and the constraint name is self-documenting.
The requires clause after the template parameter list is the right tool when you need compound constraints (combining multiple concepts with && or ||), or when you need to express constraints that span multiple parameters. It's more explicit and slightly more verbose.
The trailing requires clause — placed after the function signature but before the body — is useful when the constraint logically reads as a postcondition on the full signature, especially for member functions where you want the constraint visible near the return type.
Finally, auto parameters in abbreviated function templates are the most compact form, but they create unconstrained templates by default. Pairing a concept name before auto gives you a clean, lambda-like syntax for short utility functions. Know all four: interviewers test exactly this, and real codebases use all of them depending on context.
#include <concepts> #include <iostream> #include <numeric> #include <vector> // FORM 1: Terse syntax — concept name replaces 'typename' in template parameter // Best for: single-type constraints, maximum readability template <std::integral IntegerType> IntegerType square(IntegerType value) { return value * value; // only compiles for int, long, char, etc. } // FORM 2: requires clause after template parameter list // Best for: multi-parameter constraints or compound conditions template <typename ElementType, typename ContainerType> requires std::same_as<typename ContainerType::value_type, ElementType> && std::default_initializable<ElementType> ElementType sum_container(const ContainerType& container) { // Guaranteed: ElementType IS the container's element type AND is default-constructible ElementType total{}; // default-initialise to zero (works for int, double, etc.) for (const auto& element : container) { total += element; } return total; } // FORM 3: Trailing requires clause — after the function parameter list // Best for: constraints that reference parameter types computed from the signature template <typename Callable, typename ArgumentType> auto invoke_and_print(Callable&& function, ArgumentType argument) -> decltype(function(argument)) requires std::invocable<Callable, ArgumentType> // constraint reads naturally here { auto result = function(argument); std::cout << "Result: " << result << '\n'; return result; } // FORM 4: Abbreviated function template with concept-constrained auto // Best for: short utility lambdas and simple free functions // 'std::floating_point auto' means: deduce the type, but it MUST satisfy floating_point void print_precision(std::floating_point auto value) { std::cout << "Floating value: " << value << '\n'; } int main() { // Form 1 — works with int, long; would fail for float (not integral) std::cout << "4 squared = " << square(4) << '\n'; std::cout << "7L squared = " << square(7L) << '\n'; // Form 2 — sums a vector<double> std::vector<double> prices = {9.99, 4.50, 12.75}; std::cout << "Total price = " << sum_container<double>(prices) << '\n'; // Form 3 — invokes a lambda and prints the result auto doubler = [](int n) { return n * 2; }; invoke_and_print(doubler, 21); // prints 42 // Form 4 — works for float and double; fails for int (not floating_point) print_precision(3.14159f); print_precision(2.71828); // Uncommenting the line below gives a clean diagnostic: // square(3.14); // error: '3.14' does not satisfy 'std::integral' return 0; }
Subsumption, Overload Resolution and Why Ordering Concepts Matters
Subsumption is the mechanism that lets the compiler rank constrained overloads without ambiguity. If concept B is defined in terms of concept A (that is, satisfying B logically implies satisfying A), the compiler knows B is more constrained. When both overloads match, it picks the more constrained one — no ambiguity error, no user-side tricks needed.
The critical rule: subsumption only works through concept names, not through raw type traits. If you write the same constraint inline in two places using raw requires expressions rather than naming a concept, the compiler cannot prove they're identical — it treats them as different atomic constraints and you get an ambiguity error. This is the biggest practical gotcha in real codebases migrating from SFINAE to concepts.
Subsumption is checked syntactically at the level of normalised atomic constraints. Two atomic constraints subsume each other only if they originate from the same concept specialisation. This means copy-pasting a requires body doesn't achieve subsumption — you must factor it into a named concept.
In performance terms, none of this is runtime cost. It's purely a compile-time ranking algorithm that runs during overload resolution. The only cost is potentially longer compile times in constraint-heavy translation units, because the compiler must normalise and compare constraint sets for every candidate overload.
#include <concepts> #include <iostream> #include <iterator> #include <vector> #include <list> // --- Concept hierarchy for iterators --- // InputIterable: can be iterated forward (covers list, vector, etc.) template <typename Container> concept InputIterable = requires(Container c) { { std::begin(c) } -> std::input_iterator; { std::end(c) }; }; // RandomAccessIterable: subsumes InputIterable because it requires it PLUS random access. // This is the key: we REFERENCE InputIterable by name so subsumption works. template <typename Container> concept RandomAccessIterable = InputIterable<Container> && requires(Container c, std::size_t n) { { c[n] }; // random access by index { std::end(c) - std::begin(c) } -> std::integral; // distance is O(1) }; // --- Overload for any input-iterable container (less constrained) --- // Chosen for std::list, where random access doesn't exist template <InputIterable Container> void process(const Container& container) { std::cout << "[InputIterable path] linear scan, size computed by traversal\n"; std::size_t count = 0; for (const auto& element : container) { ++count; (void)element; } std::cout << " Element count: " << count << '\n'; } // --- Overload for random-access containers (more constrained) --- // Compiler picks THIS one for std::vector — subsumption guarantees no ambiguity. template <RandomAccessIterable Container> void process(const Container& container) { std::cout << "[RandomAccessIterable path] O(1) size, direct index access\n"; // Safe to use operator[] because the concept guarantees it std::cout << " First element: " << container[0] << '\n'; std::cout << " Size (O1): " << (std::end(container) - std::begin(container)) << '\n'; } // --- WRONG WAY: inline requires instead of concept name breaks subsumption --- // If you write the same constraint inline in both overloads, you get: // error: call to 'process_wrong' is ambiguous // because the compiler sees two different atomic constraints that happen to say the same thing. template <typename T> requires requires(T c) { std::begin(c); } // raw inline — NOT a named concept void process_wrong(const T& container) { std::cout << "overload A\n"; } // This overload cannot subsume the one above because neither references the other by name template <typename T> requires requires(T c) { std::begin(c); } && requires(T c, int n) { c[n]; } void process_wrong(const T& container) { std::cout << "overload B\n"; } int main() { std::vector<int> scores = {10, 20, 30}; std::list<int> tasks = {1, 2, 3}; process(scores); // RandomAccessIterable wins — subsumption at work process(tasks); // Only InputIterable matches — list has no operator[] // Uncommenting this causes ambiguity error — inline requires breaks subsumption: // process_wrong(scores); return 0; }
requires requires blocks. The compiler couldn't prove they were the same, so it gave up. After factoring into a named concept, the overload set compiled cleanly. The lesson: if you find yourself copy-pasting a requires expression, stop and name it. This also improves documentation.Production Patterns: requires in Class Templates, Lambdas and SFINAE Migration
Concepts aren't just for free functions. Applying them in class templates, member functions, and lambdas is where you feel the full productivity gain — and where the subtle edges emerge.
In a class template, you can constrain the entire class, or constrain individual member functions using requires clauses inside the class body. The latter is powerful: it lets you expose methods only when the type parameter supports them, giving you something close to Rust's trait-gated impl blocks without macros.
Lambdas in C++20 can use concept-constrained auto parameters, making generic lambdas finally express intent. A lambda taking std::integral auto is immediately self-documenting and gives a clean error if someone passes a float.
Migrating from SFINAE: the most common pattern to replace is std::enable_if. The mental model is direct — a requires clause replaces the enable_if condition. But watch out for the 'ill-formed, no diagnostic required' case: if a concept's requires expression checks something that is inherently ill-formed rather than substitution-dependent, the compiler might reject it at definition time rather than at point of use. This is typically caused by using volatile or reference-qualified types inside requires bodies without accounting for them.
For library authors, the most important production insight is to constrain your public API surface with concepts and leave internals unconstrained. Over-constraining internals makes future refactoring painful without changing user-visible behaviour.
#include <concepts> #include <iostream> #include <memory> #include <string> #include <vector> // --- Concept for types that can represent a monetary amount --- template <typename T> concept MonetaryType = std::floating_point<T> || std::integral<T>; // --- Class template constrained at the class level --- // The entire class only exists for MonetaryType parameters template <MonetaryType CurrencyType> class Wallet { CurrencyType balance_; public: explicit Wallet(CurrencyType initial_balance) : balance_{initial_balance} {} void deposit(CurrencyType amount) { balance_ += amount; } // Member function with its OWN additional constraint // Only available when CurrencyType supports division (i.e., floating point) // This gives us Rust-style conditional method exposure CurrencyType split_evenly(int ways) const requires std::floating_point<CurrencyType> // narrower than the class constraint { return balance_ / static_cast<CurrencyType>(ways); } CurrencyType balance() const { return balance_; } }; // --- Concept-constrained generic lambda (C++20) --- // This is the replacement for the old unconstrained [](auto x) lambdas auto format_currency = [](MonetaryType auto amount, const std::string& symbol) { std::cout << symbol << amount << '\n'; }; // --- SFINAE to Concepts migration example --- // OLD (SFINAE style — ugly, opaque): template <typename T, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0> T sfinae_double(T value) { return value * 2; } // NEW (Concepts style — readable, better diagnostics, same semantics): template <typename T> requires std::is_arithmetic_v<T> // can use type traits directly in requires T concept_double(T value) { return value * 2; } // EVEN BETTER — name the concept for reuse and subsumption: template <typename T> concept Arithmetic = std::is_arithmetic_v<T>; template <Arithmetic T> T named_concept_double(T value) { return value * 2; } // --- Concept-constrained lambda for use with standard algorithms --- // Ensures the comparator actually returns bool — catches custom Compare objects that don't auto make_descending_comparator = []<std::totally_ordered ElementType>() { return [](const ElementType& lhs, const ElementType& rhs) { return lhs > rhs; // descending order }; }; int main() { // Class template usage Wallet<double> savings{1000.0}; savings.deposit(250.50); std::cout << "Balance: " << savings.balance() << '\n'; std::cout << "Split 3 ways: " << savings.split_evenly(3) << '\n'; // Wallet<int> integer_wallet{500}; // integer_wallet.split_evenly(3); // compile error: constraint not satisfied // 'split_evenly' requires floating_point<int> which is false // Concept-constrained lambda format_currency(99.95, "$"); format_currency(150, "€"); // int satisfies MonetaryType (integral branch) // SFINAE vs Concepts — same behaviour, dramatically different readability std::cout << sfinae_double(21) << '\n'; // 42 std::cout << concept_double(21) << '\n'; // 42 std::cout << named_concept_double(21) << '\n'; // 42 // Constrained lambda producing a type-safe comparator auto int_desc = make_descending_comparator.operator()<int>(); std::vector<int> values = {3, 1, 4, 1, 5}; std::sort(values.begin(), values.end(), int_desc); for (int v : values) std::cout << v << ' '; std::cout << '\n'; return 0; }
std::floating_point as a constraint but forgetting that float and double are fine, but long double is also floating_point. If your function assumes 64-bit precision, you need an additional constraint.Designing Custom Concepts: Best Practices and Gotchas
Writing your own concepts is straightforward, but writing good ones requires discipline. A concept should be minimal, composable, and named clearly. Over-constraining is more common than under-constraining. Start with the minimum operations your algorithm actually needs, then compose.
One major gotcha: the 'ill-formed, no diagnostic required' trap. If your requires expression uses expressions that are ill-formed for any type (like attempting to create a reference to void), the compiler may reject the concept definition entirely, and the error message may not point to the user's call site. Always ensure each atomic requirement makes sense for the types you intend to support.
Another pitfall: volatile and reference qualification inside requires. If you write requires(T& a) { a = {}; } you're requiring that assigning from {} works on an lvalue reference. But if T is const int, the concept fails. This is correct but often surprises developers who forget to account for const.
Concepts should be defined before they are used. Forward declarations are not allowed. This is usually fine, but can cause ordering issues in large headers. Organise your concept definitions at the top of the translation unit or in a dedicated header.
Finally, avoid concept recursion. A concept cannot depend on itself directly or indirectly. The compiler will reject it, but the diagnostic can be cryptic. Keep your concept hierarchy acyclic.
#include <concepts> #include <iostream> #include <vector> #include <list> // --- GOOD: Minimal concept that composes well --- // A Printable type can be sent to an output stream via operator<< template <typename T> concept Printable = requires(std::ostream& os, T value) { { os << value } -> std::same_as<std::ostream&>; }; // --- GOOD: Composable refinement --- // A Loggable type is Printable AND has a name() function returning a string template <typename T> concept Loggable = Printable<T> && requires(T obj) { { obj.name() } -> std::convertible_to<std::string_view>; }; // --- BAD: Over-constrained concept that excludes valid types --- // This requires T to have a non-const operator[] returning an lvalue reference to exactly int. template <typename T> concept TooStrict = requires(T c, std::size_t i) { { c[i] } -> std::same_as<int&>; // fails for std::vector<bool> which returns proxy }; // --- BETTER: Use convertible_to for return-type constraints --- template <typename T> concept IndexableToInt = requires(T c, std::size_t i) { { c[i] } -> std::convertible_to<int>; // accepts proxy types }; // --- Common gotcha: volatile in requires --- // If T is volatile int, this concept fails because volatile int cannot bind to int& template <typename T> concept Writable = requires(T& obj) { obj = T{}; }; // Workaround: use std::remove_cvref_t to strip volatile before checking template <typename T> concept WritableBetter = requires(std::remove_cvref_t<T>& obj) { obj = T{}; }; // --- Usage example with static_assert --- struct Account { std::string name() const { return "account"; } friend std::ostream& operator<<(std::ostream& os, const Account& a) { return os << a.name(); } }; int main() { static_assert(Printable<int>); static_assert(!Printable<std::vector<int>>); // no operator<< defined static_assert(Loggable<Account>); static_assert(IndexableToInt<std::vector<int>>); static_assert(!IndexableToInt<std::list<int>>); // no operator[] std::cout << "All concept checks passed.\n"; return 0; }
- Start with the operations your generic code actually calls.
- Use
convertible_tooversame_asfor return types unless exact type matters. - Compose small concepts into larger ones — keep each concept focused on one abstraction.
- Test each concept with a static_assert on types that should and should not satisfy it.
- Avoid volatile, const, and reference qualification surprises by using std::remove_cvref_t when appropriate.
std::same_as<typename T::iterator, typename T::const_iterator> because the team thought making iterators equivalent would simplify the API. That broke every container that had separate iterator and const_iterator types (most of the STL). The fix was to drop that requirement entirely — the algorithm didn't actually need it. The lesson: never add a constraint you don't absolutely need. Every extra atomic constraint is a chance to accidentally exclude valid types.convertible_to for return-type constraints unless exact identity is needed.Learning Roadmap: Don't Learn Concepts, Master Constraints
Every C++20 tutorial throws a dozen concept examples at you and calls it a day. That's how you end up with requires requires cargo-culting in production code. The real learning path isn't about memorising syntax — it's about understanding the constraint model.
Start with the axiom: a concept is a compile-time predicate that returns a boolean. Everything else is decoration. First, learn to read error messages from constraint violations — that alone will save you more time than any feature. Second, implement a single custom concept and apply it four ways (template, auto, requires clause, static_assert). Third, internalise subsumption: the compiler's ordering rules will surprise you the first time two concepts clash in overload resolution.
Stop when you can predict, not just use, the behaviour. The difference between a junior who slaps std::regular on everything and a senior who knows when std::semiregular + custom axiom is the right call is exactly the gap between passing a compiler and shipping maintainable code.
// io.thecodeforge — c-cpp tutorial #include <concepts> #include <iostream> // A deliberately broken concept to study error messages template<typename T> concept MustBeSigned = requires(T val) { { val } -> std::convertible_to<long long>; requires std::signed_integral<T>; }; template<MustBeSigned T> T clamped_negate(T value) { return value < 0 ? value : -value; } int main() { // This will fail — 'unsigned int' is not signed std::cout << clamped_negate(42u); return 0; }
Built for 10x Developers: Writing Concepts That Scale
A 10x developer doesn't write more code — they write code that makes other code impossible to break. Concepts are your enforcement mechanism. But most devs treat them like fancy type traits and miss the real value: the associative axiom.
Here's the secret: a concept that only checks syntax (has , has size()) is a leaky abstraction. The 10x move is to embed semantic axioms that future maintainers can't circumvent. For example, pair data()std::forward_iterator with a custom IsIncrementableInSameSequence concept that asserts ++a after b = a still yields a valid iterator. That's not just a constraint — it's a contract.
Production patterns matter more than novelty. I've seen codebases burn because someone defined Printable as "has operator<<" but the actual printing required io_state_flags to be set. Write concepts that mirror your domain's invariants, not the STL's types. That's the difference between a library and a liability.
// io.thecodeforge — c-cpp tutorial #include <concepts> #include <iterator> #include <vector> // A concept that enforces a semantic invariant, not just syntax template<typename Iter, typename T> concept IsSearcheable = requires(Iter first, Iter last, T value) { { *first } -> std::same_as<T&>; { std::find(first, last, value) } -> std::same_as<Iter>; requires std::forward_iterator<Iter>; }; template<IsSearcheable<int> Iter> int first_match_or_zero(Iter start, Iter end, int target) { auto it = std::find(start, end, target); return (it != end) ? *it : 0; } int main() { std::vector<int> data = {1, 2, 3, 4, 5}; int result = first_match_or_zero(data.begin(), data.end(), 3); // Prints 3 — semantic contract holds return result; }
requires clause that actually calls the algorithm in a dummy expression. The compiler will verify it compiles — that's your free integration test.What's New for C++ in Visual Studio: Why Modern Tooling Matters
Before you write a single concept, you need an environment that understands them. Visual Studio's C++ compiler has tracked the C++20 standard closely since MSVC 16.10, shipping full concept support including requires clauses, constrained auto, and std::same_as. Why start here? Because 80% of concept errors are compiler diagnostics, not runtime bugs. Visual Studio's IntelliSense now colors constrained template parameters and marks unsatisfied constraints before build time. The real shift: you stop guessing if a concept is correct — the tool tells you the exact line where a type fails a constraint. This section covers the /std:c++20 flag toggle, the new concepts header in the Standard Library, and how the IDE's error list differentiates between a failed constraint and a normal type mismatch. The missing piece? Understanding that a compiler warning about a concept is a contract violation, not a syntax error. Visual Studio gives you the vocabulary to read those messages correctly.
// io.thecodeforge — c-cpp tutorial #include <concepts> #include <iostream> template<typename T> concept Integral = std::is_integral_v<T>; template<Integral T> T half(T value) { return value / 2; } int main() { std::cout << half(42); // OK // std::cout << half(3.14); // Compiler says: not Integral }
Dynamic Memory Management: Why Concepts Guard Resource Ownership
Dynamic memory in C++ is a contract between allocator, constructor, and destructor. Concepts make that contract enforceable at compile time — not a documentation note. Before C++20, a template accepting T would compile even if T lacked a destructor. Concepts stop that: a Destructible constraint rejects types without valid destruction. Why enforce this? Because the most expensive bugs are memory leaks from missing cleanup. This section covers the std::destructible concept, a PointerLike concept that checks operator and operator->, and a custom HeapAllocator concept requiring both allocate and deallocate members. The pattern: constrain the allocator before it touches new. Real impact: you get a static_assert when someone passes a raw array to your smart pointer template — not a segfault at 3 AM. Concepts turn dynamic memory from a runtime gamble into a compile-time guarantee.
// io.thecodeforge — c-cpp tutorial #include <concepts> template<typename A> concept HeapAllocator = requires(A& a, size_t n) { { a.allocate(n) } -> std::same_as<void*>; { a.deallocate(nullptr, 0) } noexcept; }; template<HeapAllocator A, std::destructible T> class ScopedPtr { public: explicit ScopedPtr(T* p) : ptr(p) {} ~ScopedPtr() { delete ptr; } private: T* ptr; };
Object Oriented Programming (OOP): Why Concepts Beat Abstract Base Classes
OOP in C++ traditionally uses virtual functions and inheritance to define interfaces. But virtual dispatch costs runtime indirection and forces a physical type hierarchy. Concepts replace that with structural typing: if a type has the right draw() method, it satisfies the Drawable concept — no base class needed. Why is this a breakthrough? You gain compile-time polymorphism without vtable overhead. A std::vector of Drawable constrained types is a compile-time check, not a runtime cast. This section shows how std::derived_from constraint replaces dynamic_cast, how a Cloneable concept requires a clone method without virtual inheritance, and why constrained templates scale better than class hierarchies in high-performance code. The missing link: concepts let OOP be an interface contract, not a class family. You get cleaner code that fails fast at compile time when a type doesn't fit the interface.
// io.thecodeforge — c-cpp tutorial #include <concepts> #include <iostream> template<typename T> concept Drawable = requires(T& t) { { t.draw() } -> std::same_as<void>; }; struct Circle { void draw() { std::cout << "Circle\n"; } }; struct Square { void draw() { std::cout << "Square\n"; } }; template<Drawable D> void render(D& shape) { shape.draw(); }
The Concept That Rejected Every Valid Type — Overly Strict Return-Type Constraint
begin() would be safe because both containers' begin() returns exactly the same type (iterator). The team assumed std::same_as was semantically equivalent to std::convertible_to for this case.-> std::same_as<iterator_trait> but also required a subscript operator via c[n] which list doesn't have — however the error message pointed at the return type mismatch first. The real issue was the combined constraint: the subscript operator check filtered out std::list immediately, but the compiler's diagnostic highlighted the same_as failure because it was checked earlier in the requires expression order.std::same_as to std::convertible_to for the return type of begin(). The concept should check that begin() returns something that can be used as an input iterator, not that it returns the exact same concrete type. After the fix, std::list correctly fails the operator[] check and falls through to the less-constrained overload.- Use
std::convertible_toorstd::constructible_fromfor return-type constraints unless you genuinely need exact type identity. - Constraint order in a requires expression affects which diagnostic the compiler emits first — the most restrictive constraint should come later.
- Always test concepts against multiple types including those that should fail subtly — a concept that only rejects wrong types is good; one that reports the wrong reason wastes developer time.
-> std::convertible_to<T> to each expression.g++ -std=c++20 -fconcepts-diagnostics-depth=2 myfile.cppAdd `static_assert(MyConcept<T>);` with T as the problematic typeconvertible_to not same_as unless exact type neededgrep -n 'constraint_expressions' in overloads — look for `requires requires` patterns (inline)Verify that concept B = concept A && ... (not inline copy of A's body)Compile with -ftime-report (GCC) to see which phase spends timeSimplify concept: avoid deep nesting of requires within requires| Aspect | SFINAE / enable_if | C++20 Concepts |
|---|---|---|
| Error message quality | 30+ lines of instantiation backtrace inside the library | Single line: 'T does not satisfy concept X' at call site |
| Overload ranking | Requires hacks like void_t + priority_tag to disambiguate | Subsumption handles ranking automatically via concept hierarchy |
| Readability at declaration site | enable_if<...> buried in template parameter list | Concept name reads like English: template <Sortable T> |
| Compile-time cost | Substitution attempted then discarded (expensive for many overloads) | Constraint checked before substitution — can be faster in large overload sets |
| Reusability | Type trait structs must be defined separately; no unified syntax | Named concept is a first-class entity, usable anywhere typename appears |
| Abbreviated templates | Not supported — always need template<typename T> | Supported: void f(std::integral auto value) — cleaner generic code |
| Partial specialisation | Enabled via enable_if on specialisation | Constrained partial specialisations: template<Concept T> struct S<T> |
| Standard library integration | std::enable_if_t, std::void_t, detected_t idioms | std::concepts, std::ranges concepts, iterator_concept — consistent hierarchy |
| File | Command / Code | Purpose |
|---|---|---|
| ConceptDefinition.cpp | template | Defining Concepts |
| FourSyntaxForms.cpp | template | Four Ways to Apply Concepts |
| SubsumptionDemo.cpp | template | Subsumption, Overload Resolution and Why Ordering Concepts M |
| ProductionPatterns.cpp | template | Production Patterns |
| CustomConceptDesign.cpp | template | Designing Custom Concepts |
| ConstraintDiagnostic.cpp | template | Learning Roadmap |
| AssociativeAxiom.cpp | template | Built for 10x Developers |
| ConceptsSetup.cpp | template | What's New for C++ in Visual Studio |
| DynamicMemory.cpp | template | Dynamic Memory Management |
| OopConcepts.cpp | template | Object Oriented Programming (OOP) |
Key takeaways
Common mistakes to avoid
4 patternsWriting the same constraint inline in two overloads instead of naming a concept
Checking for a method's existence without checking its return type
container.size() } -> std::convertible_to<std::size_t>. An unconstrained existence check is half a check.Applying concepts to non-deduced contexts and expecting constraint checking
Using std::same_as for return-type constraints when std::convertible_to would be appropriate
Interview Questions on This Topic
What is concept subsumption in C++20 and why does it matter for overload resolution? Can you show a case where two constrained overloads would be ambiguous without it?
A<T> && ..., then B subsumes A. When both overloads match, the compiler picks B without ambiguity. Without subsumption — if both overloads used inline requires expressions that are textually different but semantically identical — the compiler sees them as different atomic constraints and emits an ambiguity error. This is why you must use named concepts, not inline requires, when you want overload ranking.Explain the difference between a requires expression and a requires clause. When would you use each, and what happens inside a requires expression at compile time — does any code actually execute?
requires(T t) { t.f(); }). It is a compile-time check that evaluates whether the expressions inside are well-formed — no code is executed, and no code is generated. A requires clause is the grammatical construct used to attach a constraint to a template (e.g., template<typename T> requires MyConcept<T>). The requires clause can contain a single concept name, a conjunction of concepts, or a requires expression directly. You use requires expressions inside concept definitions; you use requires clauses to apply constraints to templates.If you have a concept MyRange that wraps std::ranges::range, and you define a more refined concept MySortableRange = MyRange
MyRange<T>) is distinct from an atomic constraint originating from an inline requires expression, even if they check the same thing. If you write requires(MyRange<T> && ...) in one overload and requires(requires{...} && ...) in another, the compiler treats them as different atomic constraints and the call is ambiguous. Always reference the base concept by name to enable subsumption.Frequently Asked Questions
In the vast majority of cases, yes. Concepts are strictly more expressive and readable than enable_if for constraining templates. The only edge case where SFINAE-based techniques still appear is in very old library code or when targeting compilers with partial C++20 support. For new code, there's no reason to reach for enable_if.
None whatsoever. Concepts are evaluated entirely at compile time during constraint checking and overload resolution. The generated machine code is identical to unconstrained templates that happen to be called with the correct types. The only measurable cost is potentially increased compile time in translation units with many constrained overloads.
A type trait (like std::is_integral<T>) is a struct with a ::value member — just a metaprogramming utility. A concept is a first-class language construct that integrates with overload resolution, produces better diagnostics, supports subsumption, and can be used anywhere 'typename' appears. You can use a type trait inside a concept body (requires std::is_integral_v<T>) but the concept gives the constraint a name, enables subsumption, and makes diagnostics point at the call site rather than deep inside instantiation.
No. A concept cannot refer to itself, directly or indirectly. The compiler will reject such definitions. This restriction exists to keep constraint normalisation decidable and prevent infinite loops during compilation. If you need a recursive-like check, you'll have to use SFINAE techniques or template metaprogramming.
GCC 10+ with -std=c++20, Clang 10+ with -std=c++20, and MSVC 2019 16.10+ with /std:c++20. Earlier versions may have partial or buggy support. Concepts are one of the most implemented C++20 features — by 2023 all major compilers had solid support.
20+ years shipping performance-critical C and C++ systems. Drawn from code that ran under real load.
That's C++ Advanced. Mark it forged?
9 min read · try the examples if you haven't