CodexBloom - Programming Q&A Platform

std::variant with custom types scenarios to compile in C++20 due to ambiguous overloads

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
c++20 stdvariant compilation-error C++

I've looked through the documentation and I'm still confused about I'm working with a compilation behavior when trying to use `std::variant` with custom types in C++20... I have two classes, `Foo` and `Bar`, and I want to create a variant type that can hold either. My code looks like this: ```cpp #include <variant> #include <iostream> class Foo { public: Foo() {} }; class Bar { public: Bar() {} }; using MyVariant = std::variant<Foo, Bar>; void process(MyVariant v) { std::visit([](auto&& arg) { std::cout << "Processing...\n"; }, v); } int main() { MyVariant v = Foo(); process(v); return 0; } ``` However, when I try to compile this, I get the following behavior: ``` behavior: no matching function for call to 'std::visit' ... ambiguous overload for 'operator()' ``` I've checked that both classes are default-constructible and I'm using a compatible compiler (GCC 11.2). I suspect it might be related to how lambda captures work with `std::visit`, but I need to pinpoint the scenario. I've also tried explicitly specifying the types in the lambda to no avail. Any insights into why this might be happening or how to resolve it? A colleague suggested using `std::monostate` as a default alternative type, but I would prefer not to complicate my variant types unless absolutely necessary. Could there be something I'm missing with the way I'm using `std::variant`? Any help would be appreciated! I'm working on a application that needs to handle this. Am I missing something obvious?