The last lesson ended with a chain of get_if checks and a fallback return "unknown";. That chain has a quiet failure: add a fourth event type and every chain in the program still compiles, each one silently treating the new event as unknown. In a real engine that could mean a new Delete event is accepted and ignored. You want the opposite: adding an alternative should break the build at every place that has not decided how to handle it.
std::visit(visitor, variant) does that. It looks at the active alternative and calls visitor with it, choosing the overload by normal overload resolution. Because the compiler must produce a call for every alternative, a visitor that cannot accept one of them is a compile error, not a run-time surprise.
Predict and run
#include <iostream>
#include <variant>
struct Create { int id; };
struct Adjust { int id; int delta; };
using Event = std::variant<Create,Adjust>;
struct Name {
const char *operator()(const Create&) const { return "create"; }
const char *operator()(const Adjust&) const { return "adjust"; }
};
int main() {
Event event = Adjust{2,-3};
std::cout << std::visit(Name{},event) << "\n";
return 0;
}Check your prediction
adjustName{} is an object with two operator() overloads. std::visit calls the one that takes const Adjust&, because Adjust is active. Now delete the Create overload and compile. The build fails inside the standard library, typically with a message saying the visitor is not invocable for every alternative, or that no matching function call exists. The message is long, but it points at the right problem: one alternative has no handler. Restore the overload before moving on.
A named visitor is a checklist
The project uses named structs for its visitors, one overload per event. A struct like Name reads as a complete list of the operations the engine supports, and code review can see at a glance that each one has a deliberate answer. All overloads must return the same type. std::visit has one return type, so if one overload returns int and another long, the call does not compile.
A visitor can also carry state. A visitor that applies events holds a reference to the data it changes:
#include <iostream>
#include <variant>
#include <vector>
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;
std::vector<Event> events{Adjust{-3}, Set{20}, Adjust{5}};
for (const Event& event : events) { std::visit(Apply{quantity}, event); }
std::cout << quantity << "\n";
return 0;
}25The overloads are const, yet they change quantity. Constness in C++ is shallow: a const member function cannot reseat or modify the visitor's own members, but quantity is a reference, and modifying the object it refers to is allowed. Writing int& quantity makes the visitor's power to change state visible in its declaration, which is the honest way to write it. A visitor that only reads, such as Name, holds no reference at all.
Catch-alls defeat the check
C++ lets you write a visitor that accepts anything, with a generic lambda or a template overload:
std::visit([](const auto&) { return 0; }, event); // Accepts every alternative, present and future.That is fine for a truly uniform operation, such as printing index(). For domain behavior it is the else branch from the previous lesson in a new form: a new event would compile and fall into it. A subtler hole is implicit conversion. Overload resolution is allowed to convert arguments, so a visitor can cover an alternative it never mentions:
#include <iostream>
#include <variant>
struct Show {
void operator()(double value) const { std::cout << "double " << value << "\n"; }
};
int main() {
std::variant<int, double> value = 7;
std::visit(Show{}, value);
return 0;
}double 7The active alternative is an int, yet the double overload ran, because int converts to double. No warning appears. Event structs do not convert into each other, so a visitor over Create, Adjust and Rename cannot be fooled this way. That is one more reason to give each operation a distinct struct rather than a variant of built-in types.
Lambdas as visitors, carefully
Some code builds visitors from lambdas with a small helper that inherits every lambda's call operator:
#include <iostream>
#include <string>
#include <variant>
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
std::variant<int, std::string> value = std::string("Read");
auto size = std::visit(overloaded{
[](int number) { return static_cast<std::size_t>(number); },
[](const std::string& text) { return text.size(); }}, value);
std::cout << size << "\n";
return 0;
}4The using Ts::operator()...; line brings every lambda's call operator into one overload set, and the second line is a deduction guide that lets you write overloaded{...} without naming the lambda types. Both lambdas must return std::size_t, which is why the int branch casts. This is handy for a one-off visit. For the engine's apply and export operations, named structs are clearer, easier to find, and easy to give state.
Practice
Your turn
Use struct Create { int id; int quantity; };, struct Adjust { int id; int delta; }; and struct Rename { int id; std::string name; }; in one Event variant. Write two named visitors: Label, returning "create", "adjust" or "rename", and NetChange, returning the quantity a Create adds, an Adjust's delta, or 0 for a Rename. Visit the batch Create{2,10}, Adjust{2,-3}, Rename{2,"Steel bolts"}, Adjust{2,5} and print:
create 10
adjust -3
rename 0
adjust 5
net 12#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct Create { int id; int quantity; };
struct Adjust { int id; int delta; };
struct Rename { int id; std::string name; };
using Event = std::variant<Create, Adjust, Rename>;
int main() {
std::vector<Event> batch{Create{2,10}, Adjust{2,-3}, Rename{2,"Steel bolts"}, Adjust{2,5}};
// Visit each event twice: once for its label, once for its net change.
return 0;
}Hint 1: the idea
Write one overload per event type in each visitor. Give every overload of a visitor the same return type.
Hint 2: a first step
struct Label { const char* operator()(const Create&) const { return "create"; } /* two more */ }; then call std::visit(Label{}, event) inside the loop.
Show one solution
#include <iostream>
#include <string>
#include <variant>
#include <vector>
struct Create { int id; int quantity; };
struct Adjust { int id; int delta; };
struct Rename { int id; std::string name; };
using Event = std::variant<Create, Adjust, Rename>;
struct Label {
const char* operator()(const Create&) const { return "create"; }
const char* operator()(const Adjust&) const { return "adjust"; }
const char* operator()(const Rename&) const { return "rename"; }
};
struct NetChange {
int operator()(const Create& event) const { return event.quantity; }
int operator()(const Adjust& event) const { return event.delta; }
int operator()(const Rename&) const { return 0; }
};
int main() {
std::vector<Event> batch{Create{2,10}, Adjust{2,-3}, Rename{2,"Steel bolts"}, Adjust{2,5}};
int net = 0;
for (const Event& event : batch) {
const int change = std::visit(NetChange{}, event);
std::cout << std::visit(Label{}, event) << " " << change << "\n";
net += change;
}
std::cout << "net " << net << "\n";
return 0;
}create 10
adjust -3
rename 0
adjust 5
net 12Each visitor is a complete, checked list: add a Delete alternative to Event and both std::visit calls stop compiling until you decide what a delete's label and net change are. The Rename overload returns 0 on purpose, written out rather than left to a catch-all. The checkpoint next combines a read-only checking visitor with a changing visitor, so that validation happens before any state changes.
Completion is saved in this browser only. It does not measure mastery.