Intermediate Gotchas
The variant Access That Threw
the type is allowed, but it is not active now
int main() {
std::variant<int, std::string> value = "Ada";
try {
std::cout << std::get<int>(value) << '\n';
} catch (const std::bad_variant_access&) {
std::cout << "wrong alternative\n";
}
}
Run it. Does std::get<int> convert the stored string?
Why¶
std::get<T> is an access check, not a conversion. It returns the stored value only when T
is the active alternative; otherwise it throws std::bad_variant_access. GCC emits no warning
under -Wall -Wextra because the active alternative is a runtime fact.
The fix¶
Probe safely when a mismatch is an ordinary case:
Takeaway: use get_if or check the active alternative before a variant access can fail.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo