Skip to content

Checkpoint: A Constrained Batch Helper

The Course
•
35 min study

Today you deduced callable types, constrained them with concepts and tested refusals at compile time. This checkpoint builds the engine's report helper, a generic count over a borrowed sequence, and proves it from both sides. Compile-time checks show which callables it accepts and refuses. Runtime checks show that it actually uses the predicate. Neither kind of check can stand in for the other: a constrained helper that ignores its predicate and counts every element satisfies every type check you can write.

Predict and run

Predict before running C++
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> values{1,2,3};
    std::cout << std::count_if(values.begin(),values.end(),[](int n) { return n >= 2; }) << "\n";
    return 0;
}
Check your prediction
Text
2

std::count_if is the standard library's version of this helper, and in real code you would often use it, or std::ranges::count_if. The engine still has its own count_events, because it wants a narrower, documented interface: it takes a std::span<const Event>, so callers can pass a vector, an array or part of either, and its constraint states exactly which callables are welcome. Now ask which predicate mistake this example cannot detect. A helper that ignores the predicate would print 3 here, which a careful reader notices, but with [](int) { return true; } it would print 3 as well and look correct. A test that only uses always-true predicates cannot tell a working helper from a broken one.

What you will use

  • A function template with a deduced predicate. The compiler instantiates it for each callable type, so lambdas, functors and member pointers all work.
  • A concept on the declaration. requires std::predicate<Predicate, const T&> states the contract at the call site.
  • std::invoke. It calls ordinary callables and also pointers to member functions, so &Item::in_stock works as a predicate.
  • A borrowed std::span<const T>. The helper reads elements during the call and keeps nothing.
  • Selective, none, all and empty cases. Each one catches a different mistake.

Plan before you type

  1. Write count_matching(std::span<const T> values, Predicate matches) with the constraint, counting with std::invoke(matches, value).
  2. Write a tiny check(name, condition) that prints pass or FAIL, so one failing case does not hide the others.
  3. Test a selective predicate on {1, 2, 3, 4, 5}: values of at least 4 count 2.
  4. Test a predicate that matches nothing, one that matches everything, and an empty span.
  5. Test a member function pointer over a small Item array.
  6. Add static_asserts through a concept: an int predicate is accepted, a std::string predicate is refused.
Prove it can fail

Replace the body of the loop with (void)matches; (void)value; ++count;, ignoring the predicate; the casts keep -Wunused-parameter and -Wunused-variable quiet, so the mutant still builds under -Werror. This is the project's "ignore report predicate" mutation. Every static_assert still passes, and so do the everything and empty checks. The selective, none and member function checks print FAIL. That is the point of the plan: the cases that select some elements but not all are the ones that make the predicate matter. Restore the loop afterward.

Mistakes worth checking for

  • no matching function for call to 'count_matching' with a plain array or vector. T cannot be deduced through the conversion to std::span. Write std::span<const int>(values) or give the template argument.
  • A member function pointer fails with "called object type is not a function". The loop calls matches(value) directly. Use std::invoke(matches, value).
  • The constraint says int but the call passes const int&. Keep the constraint and the actual call in agreement: constrain on const T& and call with the element as const T&.
  • The function returns int and the comparisons warn about signedness. Counts of elements are std::size_t; compare them with unsigned literals such as 2u.
  • The helper stores the predicate or a pointer to an element. It must not: the span's storage belongs to the caller and may change after the call.

Practice

Exercise

Your turn

Write count_matching as planned, then run all five behavior checks and the compile-time checks. Print:

Shell
selective: pass
none: pass
everything: pass
empty: pass
member function: pass
Generic batch checked
Your workspace C++
#include <concepts>
#include <functional>
#include <iostream>
#include <span>
#include <string>

struct Item {
    int quantity;
    bool in_stock() const { return quantity > 0; }
};

void check(const char* name, bool condition) {
    std::cout << name << ": " << (condition ? "pass" : "FAIL") << "\n";
}

int main() {
    int values[] = {1, 2, 3, 4, 5};
    Item items[] = {{3}, {0}, {7}};
    // Write count_matching, then run the checks.
    std::cout << "Generic batch checked\n";
    return 0;
}
Hint 1: the idea

Type checks prove what may be passed in. Only behavior checks with a predicate that selects some, but not all, elements prove the predicate is used.

Hint 2: a first step

Declare template<class T, class Predicate> requires std::predicate<Predicate, const T&> std::size_t count_matching(std::span<const T> values, Predicate matches), and call it as count_matching(std::span<const int>(values), ...).

Show one solution
Run the solution C++
#include <concepts>
#include <functional>
#include <iostream>
#include <span>
#include <string>

struct Item {
    int quantity;
    bool in_stock() const { return quantity > 0; }
};

template<class T, class Predicate>
requires std::predicate<Predicate, const T&>
std::size_t count_matching(std::span<const T> values, Predicate matches) {
    std::size_t count = 0;
    for (const T& value : values) {
        if (std::invoke(matches, value)) { ++count; }
    }
    return count;
}

template<class F>
concept IntPredicate = requires(std::span<const int> values, F f) { count_matching(values, f); };

void check(const char* name, bool condition) {
    std::cout << name << ": " << (condition ? "pass" : "FAIL") << "\n";
}

int main() {
    int values[] = {1, 2, 3, 4, 5};
    Item items[] = {{3}, {0}, {7}};
    const std::span<const int> view(values);

    auto by_int = [](int n) { return n >= 4; };
    auto by_text = [](const std::string& text) { return text.empty(); };
    static_assert(IntPredicate<decltype(by_int)>);
    static_assert(!IntPredicate<decltype(by_text)>);

    check("selective", count_matching(view, by_int) == 2u);
    check("none", count_matching(view, [](int) { return false; }) == 0u);
    check("everything", count_matching(view, [](int) { return true; }) == 5u);
    check("empty", count_matching(std::span<const int>{}, [](int) { return true; }) == 0u);
    check("member function", count_matching(std::span<const Item>(items), &Item::in_stock) == 2u);
    std::cout << "Generic batch checked\n";
    return 0;
}
Text
selective: pass
none: pass
everything: pass
empty: pass
member function: pass
Generic batch checked

std::predicate<bool (Item::*)() const, const Item&> is satisfied because the standard defines invocability in terms of std::invoke, and std::invoke(&Item::in_stock, item) calls item.in_stock(). The project's count_events has the same shape with T fixed to Event. Its header comment adds the obligations no concept can express: the predicate inspects but never retains its argument. Day 4 turns from reports to the engine's core promise: a batch applies completely or not at all.

Was this article helpful?

Your response is saved on this device.