C++20 std::variant throws bad_variant_access when using visit with non-variant type
This might be a silly question, but I'm working on a C++20 application that uses `std::variant` to hold either an `int` or a `std::string`. However, I'm working with a `std::bad_variant_access` exception when trying to access the value using `std::visit`. I've confirmed that the variant is indeed holding the expected type, but the code still fails. Here's a simplified version of my code: ```cpp #include <iostream> #include <variant> #include <string> std::variant<int, std::string> myVariant; void printVariant() { std::visit([](auto&& arg) { std::cout << "Value: " << arg << '\n'; }, myVariant); } int main() { myVariant = 42; printVariant(); // This works fine. myVariant = std::string("Hello, World!"); printVariant(); // This works fine too. myVariant = 0; // Resetting the variant to int. try { // Intentionally setting to a string to test behavior handling myVariant = std::string("Test"); printVariant(); myVariant = std::monostate(); // Invalid state printVariant(); // This line throws bad_variant_access } catch (const std::bad_variant_access& e) { std::cerr << "Exception: " << e.what() << '\n'; } return 0; } ``` In the above code, when I set `myVariant` to `std::monostate()` and then call `printVariant()`, it throws a `std::bad_variant_access`. I thought `std::visit` should handle this gracefully, given that I'm using a lambda function to access the value. How should I handle cases where the variant might be in a state that doesn't match any of the valid types? Any best practices for behavior handling with `std::variant`? I've looked at the [C++ Standard Library documentation](https://en.cppreference.com/w/cpp/utility/variant) but couldn't find anything that addresses this specific scenario. Also, is there a way to check if the variant is in a valid state before visiting it? I want to avoid this kind of runtime behavior in the first place. I'm working on a application that needs to handle this. Thanks in advance! Is there a better approach? I'm working in a macOS environment. Am I approaching this the right way? This is for a CLI tool running on CentOS. For reference, this is a production application. Is this even possible?