3 ms·
> To work around this, you need to wrap the strings in newtypes That is certainly an option, but actually std::variant<string, string, shared_ptr<Node>> does s
by quietbritishjim 6y ago
> To work around this, you need to wrap the strings in newtypes
That is certainly an option, but actually std::variant<string, string, shared_ptr<Node>> does still work for most operations (std::visit is not one of them though). So another option is to use that typelist directly and switch to index-based access, at least for those entries:
if (std::string* s = std::get_if<0>(myVariant)) {
// Use s
}
else if (std::string* s = std::get_if<1>(myVariant)) {
// Use s
}
else if (NodePtr* node = std::get_if<2>(myVariant)) {
// Use node
}
else {
throw std::logic_error("Unknown variant entry");
}
At that point you'll probably want to define an enum (an old-school one so it implicitly converts to int) to identify the cases symbollically, which admittedly is pretty messy given that it's up to you, the maintainer, to keep the enum in sync with the actual type list in the variant. But it's hardly the worst coding sin ever, and better than any alternative I can think of (short of switching to another language). As you can see from my comment further down, I think a chain of if statements is cleaner than std::visit anyway, precisely because of the complexity problems of std::visit discussed in the article.