3 ms·
C++ has pattern matching through overloading.
by mgaunard 2y ago
C++ has pattern matching through overloading.
- tialaramex 2y agoHow do you figure?
- mgaunard 2y agoI don't understand the question. Here is the first example I found on Google if that helps you understand. std::variant<Fluid, LightItem, HeavyItem, FragileItem> package; std::visit(overload{ [](Fluid& ) { std::cout << "fluid\n"; }, [](LightItem& ) { std::cout << "light item\n"; }, [](HeavyItem& ) { std::cout << "heavy item\n"; }, [](FragileItem& ) { std::cout << "fragile\n"; } }, package);
- tialaramex 2y agoBut that's not really even a pattern match? Here's what a pattern match looks like: [This is from day 10 of last year's Advent of Code.] match (state, pipe) { (State::None, Pipe::Ground) => { if inside { n += 1; } } (State::None, Pipe::Vert) => { inside = !inside; } (State::None, Pipe::Se) => { state = State::South; } (State::None, Pipe::Ne) => { state = State::North; } // Horizontal lines make no difference to anything (State::North | State::South, Pipe::Horiz) => {} // U-turns (State::South, Pipe::Sw) | (State::North, Pipe::Nw) => { state = State::None; } // Form a vertical line (State::South, Pipe::Nw) | (State::North, Pipe::Sw) => { inside = !inside; state = State::None; } _ => { panic!("Unexpected sequence {state:?} {pipe:?}"); } }
- mgaunard 2y agoThis is the exact same thing except you're visiting two arguments at a time. Guess what, the same syntax I gave supports exactly that as well.