Today you gave each event its own struct, joined them in a closed std::variant, and dispatched on them with named visitors. This checkpoint puts those pieces behind one decision the engine makes for every event: is this request allowed, and if so, what does it change? The two halves must stay separate. A visitor that checks and changes in the same breath can leave an item half-updated when a check fails partway through, and it makes the rule impossible to test without also testing the change. Here a read-only visitor decides, and only then does a second visitor publish the change.
Predict and run
#include <iostream>
#include <variant>
struct Adjust { int delta; };
struct Set { int value; };
using Event = std::variant<Adjust,Set>;
struct Apply {
int& quantity;
void operator()(const Adjust& event) const { quantity += event.delta; }
void operator()(const Set& event) const { quantity = event.value; }
};
int main() {
int quantity = 10;
Event event = Adjust{-3};
std::visit(Apply{quantity},event);
std::cout << quantity << "\n";
return 0;
}Check your prediction
7Apply trusts its input completely. Give it Adjust{-30} and the quantity becomes -20, an inventory nobody can have. Give it Adjust{2147483647} and the addition overflows a signed int, which is undefined behavior, not a wraparound you can test for afterward. A public engine must check the delta range first, then check that the result stays in 0..1000, and only then write. Checking after the write is too late for both problems.
What you will use
- Distinct event structs.
Adjust{delta}andRename{name}carry only the fields their operation needs. - A closed variant.
using Event = std::variant<Adjust, Rename>;lets one vector hold the whole sequence. - A read-only visitor.
Checktakesconst Item&and returns an empty string for success or a reason for rejection. Because its reference isconst, the compiler forbids it from changing the item. - A changing visitor.
ApplyholdsItem&and is only called afterCheckhas said yes. - Explicit overloads. One per alternative in each visitor, with no generic catch-all.
Plan before you type
- Define
Item { std::string name; int quantity; }, the two event structs and theEventvariant. - Write
Check. For an Adjust, reject a delta outside -1000..1000 first, then compute the new quantity and reject anything outside 0..1000. For a Rename, reject an empty name or one longer than 40 characters. - Write
Applywith one assignment per overload. - Write a
Labelvisitor that prints each event asadjust -3orrename "Steel bolts". - In
main, loop over the events. Print the label, then eitherokafter applying, orrejected (reason)without applying. - Print the final item.
The order inside step 2 matters. Checking the delta range before adding keeps the sum within -1000..2000, so the addition can never overflow even though the starting quantity comes from the caller.
Prove it can fail
Once your output matches, move the std::visit(Apply{item}, event) call above the Check call, so every event is applied before it is checked. Run again. The final line becomes Steel bolts -8: the rejected -20 has leaked into the item, and every later check now judges a state that already includes its own event, so the second reason reads -33 and the last adjustment is wrongly rejected. Rejections that print correctly prove nothing about state; only the final item reveals the bug. Restore the order afterward.
Mistakes worth checking for
- Every rejection reason is correct, but the final quantity is wrong. The changing visitor runs before or regardless of the check. Apply only inside the success branch.
std::visitfails to compile with a long template error. One visitor is missing an overload, or two overloads return different types, such asstd::stringandconst char*. Return the same type from every overload.Checkcompiles even though it modifies the item. It holdsItem&instead ofconst Item&. Make the referenceconstso the compiler enforces the read-only role.- The rename prints an empty name as accepted. The check tested
size() > 40but notempty(). Test both ends of every range. - The adjustment check uses
item.quantity + event.deltabefore checking the delta. It works for these inputs, but an extreme delta can overflowint. Check the operand range first.
Practice
Your turn
Start from the item Bolts with quantity 10. Process these events in order: Adjust{-3}, Adjust{-20}, Rename{""}, Rename{"Steel bolts"}, Adjust{5}. Check each with a read-only visitor and apply only accepted events. Print:
adjust -3: ok
adjust -20: rejected (quantity would be -13)
rename "": rejected (empty name)
rename "Steel bolts": ok
adjust 5: ok
Steel bolts 12#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct Item { std::string name; int quantity; };
struct Adjust { int delta; };
struct Rename { std::string name; };
using Event = std::variant<Adjust, Rename>;
int main() {
Item item{"Bolts", 10};
std::vector<Event> events{Adjust{-3}, Adjust{-20}, Rename{""}, Rename{"Steel bolts"}, Adjust{5}};
// Check each event, apply only accepted ones, then print the item.
return 0;
}Hint 1: the idea
Two visitors with two jobs. Check sees a const Item& and returns a reason; Apply sees an Item& and is called only when the reason is empty.
Hint 2: a first step
Write struct Check { const Item& item; std::string operator()(const Adjust& e) const { ... } std::string operator()(const Rename& e) const { ... } }; and build the reason with "quantity would be " + std::to_string(next).
Show one solution
#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct Item { std::string name; int quantity; };
struct Adjust { int delta; };
struct Rename { std::string name; };
using Event = std::variant<Adjust, Rename>;
struct Check {
const Item& item;
std::string operator()(const Adjust& event) const {
if (event.delta < -1000 || event.delta > 1000) { return "delta out of range"; }
const int next = item.quantity + event.delta;
if (next < 0 || next > 1000) { return "quantity would be " + std::to_string(next); }
return "";
}
std::string operator()(const Rename& event) const {
if (event.name.empty()) { return "empty name"; }
if (event.name.size() > 40) { return "name too long"; }
return "";
}
};
struct Apply {
Item& item;
void operator()(const Adjust& event) const { item.quantity += event.delta; }
void operator()(const Rename& event) const { item.name = event.name; }
};
struct Label {
std::string operator()(const Adjust& event) const { return "adjust " + std::to_string(event.delta); }
std::string operator()(const Rename& event) const { return "rename \"" + event.name + "\""; }
};
int main() {
Item item{"Bolts", 10};
std::vector<Event> events{Adjust{-3}, Adjust{-20}, Rename{""}, Rename{"Steel bolts"}, Adjust{5}};
for (const Event& event : events) {
const std::string reason = std::visit(Check{item}, event);
std::cout << std::visit(Label{}, event) << ": ";
if (reason.empty()) {
std::visit(Apply{item}, event);
std::cout << "ok\n";
} else {
std::cout << "rejected (" << reason << ")\n";
}
}
std::cout << item.name << " " << item.quantity << "\n";
return 0;
}adjust -3: ok
adjust -20: rejected (quantity would be -13)
rename "": rejected (empty name)
rename "Steel bolts": ok
adjust 5: ok
Steel bolts 12The second adjustment sees quantity 7, the value after the first accepted event, which is why the reason says -13 rather than -10. Each decision is made against the current state and published only after it passes. That works for one event at a time. Day 4 extends it to a whole batch, where a late rejection must undo earlier accepted events too, and the engine gets there by checking and applying against a staged copy instead of the live item. First, Day 2 gives the engine rules it owns.
Completion is saved in this browser only. It does not measure mastery.