Visiting variants
In the preceding example, we showed how when we had a variable std::variant<int, double> v, calling std::get<double>(v) would give us the current value if the variant currently held a double, but would throw an exception if the variant held an int. This might have struck you as odd--since int is convertible to double, why couldn't it just have given us the converted value?
We can get that behaviour if we want it, but not from std::get. We have to re-express our desire this way: "I have a variant. If it currently holds a double, call it d, then I want to get double(d). If it holds an int i, then I want to get double(i)." That is, we have a list of behaviors in mind, and we want to invoke exactly one of those behaviors on ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access