According to cppreference std::get
for variant
throws std::bad_variant_access
if the type contained in the variant
is not the expected one. This means that the standard library has to check on every access (libc++).
What was the rationale for this decision? Why is it not undefined behavior, like everywhere else in C++? Can I work around it?
I think I found it!
Seems like the reason can be found under the "Differences to revision 5" in the proposal :
The Kona compromise: f !v.valid(), make get<...>(v) and visit(v) throw.
Meaning - that the variant has to throw in "values_by_exception" state. Using the same if
we can always throw.
Even knowing this rational I personally would like to avoid this check.
The *get_if
work around from Justin's answer seems good enougth for me (at least for library code).