Library contents

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

  1. Start with Text "2" where an integer is required
  2. Do this Check or cast the type
  3. Result Type mismatch
A string containing a digit is still a string. Parsing would be a separate operation.

Syntax

C++ 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
./lesson

Check 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.

ResultReview fare type
lesson.cpp
#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;
}
Output
Review fare type

The imported value holds text. The desk flags the fare before treating it as a number.

Advertisements

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.

GivenInteger 36
Worked resultNumber accepted

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.

GivenText “36”
Worked resultReview field type

What to watch for

Use std::get_if when a missing alternative is an ordinary input case.

Documentation for std::bad_variant_access