4 ms·
I actually prefer the overloads or constexpr branches to make_visitor because it's easier to see what's going on. Anyway, until C++ gets pattern matching for t
by nly 6y ago
I actually prefer the overloads or constexpr branches to make_visitor because it's easier to see what's going on.
Anyway, until C++ gets pattern matching for the simple cases make_visitor is the best we can do.
If you want advanced variant use cases you can always use boost::variant (v1) which supports multivisitation, which coupled with templates is exceptionally powerful.
If you want to go even further with open multimethods you can checkout the yomm2 library.
As always C++ gives you options
- jsnell 6y agoThe constexpr version looks like it can't guarantee at compile time that all the variants are handled. At least to me, statically ensuring full coverage seems like an absolutely crucial part of effectively using sum types. Is there some kind of deeper magic going on in the "constexpr if" version than it looks like?
- nly 6y agoNo I think you're right, but this is fine. There may be instances where you don't want to handle every possible data type and other values should result in a no-op. If you want full coverage then visitation guarantee that statically. Multi-visitation over m variants each with N possible types also does this statically with N^m instantiations. This balloons quickly, which is why I mentioned yomm2, which can add these handlers dynamically at runtime for polymorphic types.
- bvaldivielso 6y agoI think it can guarantee full coverage. You just need an else branch with `static_assert(false)` or something along those lines
- jsnell 6y agoIf you need to put in the fallback "else" yourself, with no error or even warning if you forget to do so, it's not much of a guarantee :) (And thinking about this a bit more, there's presumably also the opposite case: if you add a branch for a type that's not a member of the variant / remove a type from a variant without updating all the visitors, it'd just happily compile with no indication that anything is wrong.)
- nyanpasu64 6y agostatic_assert(false) fails to compile even if it appears in an if-constexpr branch that isn't taken. You need a dependent false value, templated by the type passed into the lambda. And yes, C++ is an endless pit of horrors.