C++ std::bad_variant_access
A request for the inactive alternative of a variant throws bad_variant_access.
A simple example
std::bad_variant_access
- Start with Text "2" where an integer is required
- Do this Check or cast the type
- Result Type mismatch
Syntax
std::get<int>(fare)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonCheck the type of an imported fare
A transit app imports fares from two ticket machines. One machine sends the word “free” in a field normally filled with a whole number, so the importer needs to flag the record for review.
#include <iostream>
#include <variant>
#include <string>
int main() {
std::variant<int, std::string> fare = std::string("free");
try {
std::cout << std::get<int>(fare) << '\n';
} catch (const std::bad_variant_access&) {
std::cout << "Review fare type\n";
}
return 0;
}
Review fare type
The imported value holds text. The desk flags the fare before treating it as a number.
Import a museum headcount
The counter sends the number 36 as an integer object. The import expects an integer value. Flag a text field for review before calculating a total.
Review a quoted fare
A new terminal sends its fare as text in a field that previously carried an integer. The import expects an integer value. Flag a text field for review before calculating a total.
What to watch for
Use std::get_if when a missing alternative is an ordinary input case.