4 ms·
I'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
by maxlybbert 9y ago
I'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.