3 ms·
Rather than using std::visit, you can just use a chain of if statements with get_if [1]. You keep the most important benefits of std::variant but the code is mu
by quietbritishjim 5y ago
Rather than using std::visit, you can just use a chain of if statements with get_if [1]. You keep the most important benefits of std::variant but the code is much more readable (IMO).
[1] https://news.ycombinator.com/item?id=25316192 https://news.ycombinator.com/item?id=25316192
- jcelerier 5y agoInteresting, I find the list of of ifs much less easy on the eyes. I wonder why that is.
- quietbritishjim 5y agoAgreed that it's a personal preference. If you geniunely have a standalone function, like print_type shown here, then std::visit seems roughly even with std::get_if to me (but I'd tend to use the latter for consistency with my other code). std::visit would clearly come out ahead if you had some sort of complex nested variant and you called out to other visitors. get_if is clearly ahead IMO if you're using a variant in passing in a broader function, and especially if you when you want to use control flow (if you return in an if branch you return from the wider function).
- jcelerier 5y agoYes, this case (checking for a type and returning early) is pretty much my only usage of get_if (and in this case it makes a lot of sense)