advanced patterns When Using std::optional with Custom Types and std::variant in C++20
I'm not sure how to approach I'm upgrading from an older version and I'm prototyping a solution and I've been struggling with this for a few days now and could really use some help... I'm working with unexpected behavior when trying to use `std::optional` in combination with `std::variant`. I have a custom type `MyType`, and I want to return an `std::optional<std::variant<MyType, int>>` from a function, but I'm running into issues when trying to access the variant. Here's a simplified version of my code: ```cpp #include <iostream> #include <variant> #include <optional> #include <string> class MyType { public: MyType() : value("Default") {} MyType(std::string v) : value(v) {} std::string value; }; std::optional<std::variant<MyType, int>> getValue(bool condition) { if (condition) { return MyType("Hello"); } else { return 42; } } int main() { auto result = getValue(true); if (result.has_value()) { std::visit([](auto&& arg) { std::cout << arg.value << std::endl; }, *result); } return 0; } ``` When I run this code, I get a compilation behavior: ``` behavior: no matching function for call to βstd::visit(...)β ``` I suspect that the question might be related to how `std::variant` is handling my custom type, but I'm not sure what I'm doing wrong. I've verified that `MyType` has a valid copy constructor and is not throwing any exceptions. Is there something specific I need to do to make `std::visit` work with `std::variant` when it contains custom types? Any guidance would be greatly appreciated. Is there a better approach? Cheers for any assistance! What are your experiences with this?