4 ms·
C++ match expressions would make std::variant a really nice alternative. I assume there is already a proposal out?
by adgasf 8y ago
C++ match expressions would make std::variant a really nice alternative.
I assume there is already a proposal out?
- Chabs 8y agostd::visit mostly allows you to do that already: https://coliru.stacked-crooked.com/a/be5c44281eea8bc4 https://coliru.stacked-crooked.com/a/be5c44281eea8bc4 Then only unfortunate missing piece of the puzzle is that there's no trivial way to create a closure out of this, so it requires a bit more manual work to propagate local state to the visitor.
- ddalcino 8y agoIf you build your visitor out of lambdas, instead of a struct, you can propagate local state to the visitor easily by using lambda captures. There are good examples of this approach at https://en.cppreference.com/w/cpp/utility/variant/visit https://en.cppreference.com/w/cpp/utility/variant/visit
- Chabs 8y agoUnfortunately, you can't leverage template substitution rules with the lambda approach. And that's really necessary if you want to have actual powerful match expressions.
- pjmlp 8y agoFor those working with C++ an answer might come in C++23. http://open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1371r0.pdf http://open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1371r0....
- monk_the_dog 8y agoPattern matching is on many people's radar, including the "Direction Group" (See: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0939r0.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p093...). This proposal was discussed at the committee meeting last month: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1371r0.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p137... I'd love to see it standardized in 23, but I have no idea how likely that is. (It definately won't be in c++-20, which is now closed except for tweaks).
- exitb 8y agoFor reference, Rust version shows how much simpler that could be with pattern matching - https://gist.github.com/km216/aad5c0fa11f32aa562af2370a32208cb https://gist.github.com/km216/aad5c0fa11f32aa562af2370a32208...
- ddalcino 8y agoUntil C++2z rolls out with match support, you can roll your own. Nikolai Wuttke gave a lecture at MeetingCpp 2018 (https://www.youtube.com/watch?v=CELWr9roNno https://www.youtube.com/watch?v=CELWr9roNno) that presents code that lets you do this: // Client visitor code match( thingy, [](const PurpleThingy& ) {std::cout << "purple thingy\n";}, [](const LittleThingy& ) {std::cout << "little thingy\n";}, [](const auto& ) {std::cout << "any other type\n";} ); Working example: https://coliru.stacked-crooked.com/a/dfed39bc7fcdfb01 https://coliru.stacked-crooked.com/a/dfed39bc7fcdfb01
- deleted 8y ago[deleted]