std variant and the power of pattern matching
summary
Shows that using std::variant plus an overloaded visitor yields exhaustive, type-safe handling of union-like cases and maps naturally to state machines and event objects. A mini space‑battle demo and an event-printing demo compile and run, but not zero cost: compile time +~200 ms, binary ~+1–2 KB, runtime +~1–3 ns in examples. Notes a real pitfall—dangling references when a handler mutates the variant—and the mitigation of returning an optional new state.
AI-written summary · about
chapters (30)
- 0:00Intro
- 3:02Traditional: enum + state variables
- 5:07Wanted: Modeling states explicitly
- 6:03Definition: Sum Type
- 6:33Tagged Union
- 7:57Variant in C++ 17
- 8:50Getting at the current value
- 10:36Using std::visit()
- 12:06Matching values
- 13:41Native pattern matching: Haskell (1)
- 14:59Sum types & pattern matching
- 15:20Native pattern matching: Haskell (2)
- 16:16Native pattern matching: Rust
- 16:45Wanted: Pattern matching a C++ variant
- 17:04overloaded helper
- 18:45Writing a match() function
- 19:08Using the match() function
- 20:09Variant libraries
- 21:12Match function
- 22:41Reminder: Space game state machine
- 23:44Implementing state-specific logic
- 24:52State transitions: pitfall (2)
- 28:19Comparison
- 32:41Event handling
- 34:09Traditional approaches Event ID plus untyped payload (Win32 API)
- 41:22Recommendation
- 42:20More examples
- 45:38Native pattern matching proposal
- 53:04Space Game: Opponent state machine
- 56:05State transitions: pitfall (1)
related talks
59mThe Many Variants of std::variant
59mFunctional Programming: data
49mA Journey Into Non-Virtual Polymorphism in C++
48mBack to Basics: Cpp Value Semantics
01h 01mC++ Design Patterns - The Most Common Misconceptions (2 of N)
01h 37mExtending and Simplifying C++: Thoughts on Pattern Matching using `is` and `as`
01h 01mUsing Modern C++ to Eliminate Virtual Functions
01h 01mEmbracing (and also Destroying) Variant Types Safely
