3 ms·
Not the same as what the article is trying to accomplish, which is an exhaustive match (i.e., any unmatched value is guaranteed to fail at compile time). For e
by atombender 9y ago
Not the same as what the article is trying to accomplish, which is an exhaustive match (i.e., any unmatched value is guaranteed to fail at compile time).
For example, consider a parser that matches on tokens. If you add a new token, the match should fail, because you want to guarantee, at compile-time, that every possible case is handled.
This is one reason that the lack of sum types in Go is so painful, to the point that someone wrote a special library for it [1].
[1] https://github.com/BurntSushi/go-sumtype https://github.com/BurntSushi/go-sumtype
- maxlybbert 9y agoI'm familiar with the approach from other languages that the article tries to import into C++ before concluding that the designers should watch out for language envy (incidentally, Stroustrup wrote a paper on efficient type matches: http://stroustrup.com/OpenPatternMatching.pdf http://stroustrup.com/OpenPatternMatching.pdf ). The author picks a particular approach and then shows that the approach isn't satisfactory. But the author did not go back to try another approach. If the visitor approach is acceptable but has_alternative is not, get<> also accepts index values (as numeric template parameters, e.g., get<0>(v), get<1>(v), etc.) and variant has a method called index() to give a numeric value saying what the current type is. This is easy enough to use in a switch statement: std::variant<int, double, std::string> v; ... switch (v.index()) { case 0: std::printf("%d\n", std::get<0>(v)); break; case 1: std::printf("%f\n", std::get<1>(v)); break; case 2: std::puts(std::get<2>(v).c_str()); break; } In this case you can add a default: branch and throw an error for unhandled types, or you can hope that the compiler issues a warning about a missing case (index is constexpr, so it's possible for the compiler to know that you've missed something). It's not as good as a compile error, but it might be good enough.