example4_error_handling.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
#include <variant>
#include <stdexcept>

int main() {
    std::variant<int, float, std::string> v = 42;
    
    try {
        std::cout << std::get<float>(v) << std::endl;
    } catch (const std::bad_variant_access& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }
    
    return 0;
}
Back to variant