An unconstrained template accepts any type at the call and only discovers a problem while compiling its body. The caller who passed a lambda taking a string gets an error about matches(value) inside a loop they did not write, which is the template author's code, not theirs. Worse, the requirement itself is invisible: a reader of the declaration template<class Predicate> has to read the body to learn what Predicate must be.
A concept, from C++20, is a named compile-time requirement on types. Putting one on a template's declaration states the requirement where readers look first, and makes the compiler check it before it looks at the body. A call that does not meet it is rejected at the call site, with a message that names the unmet requirement. Include <concepts> for the standard ones.
Predict and run
#include <iostream>
#include <concepts>
template<class Predicate>
requires std::predicate<Predicate,int>
bool test(int value, Predicate matches) { return matches(value); }
int main() {
std::cout << test(3,[](int n) { return n > 0; }) << "\n";
return 0;
}Check your prediction
1std::predicate<Predicate, int> is true when a Predicate can be invoked with an int and its result is boolean-testable, meaning usable in an if. The lambda satisfies both, so the call compiles and returns true. Now replace the lambda with [](const std::string& s) { return s.empty(); }, adding #include <string>, and compile. Clang answers at the call:
c.cpp:7:12: error: no matching function for call to 'test'
c.cpp:5:6: note: candidate template ignored: constraints not satisfied [with Predicate = (lambda at c.cpp:7:20)]
c.cpp:4:10: note: because 'std::predicate<(lambda at c.cpp:7:20), int>' evaluated to false
note: because 'regular_invocable<(lambda at c.cpp:7:20), int>' evaluated to false
note: because 'invocable<(lambda at c.cpp:7:20), int>' evaluated to falseRead it top down: the call has no match, the only candidate was ignored because its constraint failed, and the notes explain why, one concept at a time, down to "this lambda cannot be invoked with an int". Restore the valid lambda.
Three ways to say the same thing
The requires clause above is the most general form. For a requirement on a single parameter there are two shorter spellings, and all three mean the same:
template<class Predicate> requires std::predicate<Predicate, int>
bool test(int value, Predicate matches);
template<std::predicate<int> Predicate> // The concept's first argument is filled in.
bool test(int value, Predicate matches);
bool test(int value, std::predicate<int> auto matches); // Abbreviated function template.Use whichever reads best. The project uses the requires clause on count_events, because the constrained argument type, const Event&, is long enough to deserve its own line.
Writing your own concept
A requires expression lists operations that must be valid, and a concept gives the list a name. The concept below accepts any type with a quantity member convertible to long. Its total takes a std::span<const T>, which for now you can read as "a read-only view of some Ts in a row", like a const vector reference that also accepts a plain array. Day 5 covers std::span properly.
#include <concepts>
#include <iostream>
#include <span>
#include <string>
template<class T>
concept HasQuantity = requires(const T& item) {
{ item.quantity } -> std::convertible_to<long>;
};
struct Item { std::string name; int quantity; };
struct Pallet { long quantity; };
struct Label { std::string text; };
static_assert(HasQuantity<Item>);
static_assert(HasQuantity<Pallet>);
static_assert(!HasQuantity<Label>);
template<HasQuantity T>
long total(std::span<const T> items) {
long sum = 0;
for (const T& item : items) { sum += item.quantity; }
return sum;
}
int main() {
Item items[] = {{"Bolts", 7}, {"Nuts", 5}};
Pallet pallets[] = {{400}, {350}, {250}};
std::cout << total<Item>(items) << " " << total<Pallet>(pallets) << "\n";
return 0;
}12 1000The { expression } -> concept form checks both that the expression compiles and that its type satisfies the concept. The static_assert lines are tests that run in the compiler: they document which types meet the requirement and fail the build if that changes. The calls name T explicitly because a C-style array converts to a std::span, but template deduction does not look through that conversion.
Constraints choose between overloads
Constraints also take part in overload resolution. A call goes to the overload whose constraints are satisfied:
#include <concepts>
#include <iostream>
void describe(std::integral auto value) { std::cout << "whole number " << value << "\n"; }
void describe(std::floating_point auto value) { std::cout << "measurement " << value << "\n"; }
int main() {
describe(12);
describe(2.5);
return 0;
}whole number 12
measurement 2.5Unlike the visitor trap on Day 1, the int cannot drift to the floating-point overload, because the constraint rejects that overload outright rather than ranking a conversion.
What a concept cannot check
A concept checks syntax: which expressions compile and what types they produce. It does not check behavior. [](int) { return true; } is a perfectly valid std::predicate<int>, and a count that uses it is a perfectly wrong report. A lambda that increments a global counter on every call also compiles. The standard actually defines std::predicate in terms of std::regular_invocable, whose documented meaning includes "calling it does not change the arguments and gives equal results for equal inputs". The compiler cannot verify that, so it is a semantic requirement: part of the contract, unchecked by the build. The engine's header writes its semantic requirements in a comment beside the constraint, and tests are what enforce them.
Practice
Your turn
Write select_count(std::span<const int> values, Predicate matches) constrained with std::predicate<Predicate, int>. Add static_asserts showing that a lambda taking int satisfies the concept and a lambda taking const std::string& does not. Then count values in {3, -1, 8, 0, -6} that are positive, that are negative, and that are zero:
positive: 2
negative: 2
zero: 1#include <concepts>
#include <iostream>
#include <span>
#include <string>
int main() {
int values[] = {3, -1, 8, 0, -6};
// Write select_count, two static_asserts and three counts.
return 0;
}Hint 1: the idea
The constraint states what the predicate must accept; the static_asserts prove the constraint says what you meant.
Hint 2: a first step
Give each lambda a name with auto positive = [](int n) { return n > 0; };, so you can write static_assert(std::predicate<decltype(positive), int>);.
Show one solution
#include <concepts>
#include <iostream>
#include <span>
#include <string>
template<class Predicate>
requires std::predicate<Predicate, int>
std::size_t select_count(std::span<const int> values, Predicate matches) {
std::size_t count = 0;
for (int value : values) { if (matches(value)) { ++count; } }
return count;
}
int main() {
int values[] = {3, -1, 8, 0, -6};
auto positive = [](int n) { return n > 0; };
auto negative = [](int n) { return n < 0; };
auto zero = [](int n) { return n == 0; };
auto wrong = [](const std::string& text) { return text.empty(); };
static_assert(std::predicate<decltype(positive), int>);
static_assert(!std::predicate<decltype(wrong), int>);
std::cout << "positive: " << select_count(values, positive) << "\n";
std::cout << "negative: " << select_count(values, negative) << "\n";
std::cout << "zero: " << select_count(values, zero) << "\n";
return 0;
}positive: 2
negative: 2
zero: 1Here values converts to std::span<const int> without help, because that parameter's type is fixed and only Predicate is deduced. The three counts add up to 5, the number of values, a cheap cross-check that the conditions do not overlap or leave gaps. The negative static_assert is the interesting one: it proves at compile time that a wrong callable is rejected. The next lesson builds a whole test strategy around that idea.
Completion is saved in this browser only. It does not measure mastery.