(no title)
andrewg | 5 years ago
std::variant<int, bool, double> options;
options = true;
bool value = std::get<bool>(options);
bool has_bool = std::holds_alternative<bool>(options);
// or test which alternative is held
if (auto i = std::get_if<int>(&options)) {
// do something with int
} else if (auto b = std::get_if<bool>(&options)) {
// do something with bool
} else {
// do something with double
}
nicoburns|5 years ago
- No pattern matching means your stuck with the awkward if-elseif-else
- It doesn't check that you've accounted for every possible variant.
- You can only hold one variant of each type: you can't have two variants that both contain a string.
- The specific instance isn't it's own type, so you can't implement methods on it.
etalian|5 years ago
It is, in spirit, an implementation of the inspect proposal [1], but with a (subjectively) much simpler and more powerful syntax (the grammar of the entire language is fully LALR(1) without ambiguities).
[1] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p137...
TFortunato|5 years ago
pjmlp|5 years ago
TFortunato|5 years ago
zeotroph|5 years ago
Also this has "language support" in the sense that it is (again) implemented via template meta programming, i.e. the compile time is impacted quite heavily.
See "std::visit is everything wrong with modern C++": https://bitbashing.io/std-visit.html
This standards proposal would add proper match (named, of course, inspect) support: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p009...
dunefox|5 years ago