Skip to content

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?

Answer
wrong alternative

The requested alternative is present in the type, but not in this value.

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:

if (const int* number = std::get_if<int>(&value))
  std::cout << *number << '\n';

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

Open in Compiler Explorer ↗ Quiz this entry