CodexBloom - Programming Q&A Platform

std::variant not able to switch types correctly in custom visitor implementation

πŸ‘€ Views: 110 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
c++17 std-variant visitor-pattern C++

I'm getting frustrated with I'm working with an scenario with `std::variant` when trying to implement a custom visitor pattern. I have defined a `variant` type that can hold either an `int` or a `std::string`, and I've written a visitor to handle the different types. However, when I try to call `std::visit`, I get a compilation behavior related to the visitor's overloads. Here’s a simplified version of what I’m trying to do: ```cpp #include <iostream> #include <variant> #include <string> struct Visitor { void operator()(int i) const { std::cout << "Integer: " << i << std::endl; } void operator()(const std::string& s) const { std::cout << "String: " << s << std::endl; } }; int main() { std::variant<int, std::string> var = 42; std::visit(Visitor(), var); var = "Hello, world!"; std::visit(Visitor(), var); return 0; } ``` When I compile this code using g++ 9.3.0, I get the following behavior: ``` behavior: no matching function for call to β€˜std::visit(Visitor&, std::variant<int, std::string>&)’ ``` I've checked that the variant type is correctly defined and that the visitor seems to have the correct overloads for the types in the variant. I've also tried using `std::monostate` as a default type in the variant, but that didn't seem to help either. What could be going wrong here? Are there any special considerations I should be aware of when using `std::variant` with custom visitors? Any help would be appreciated! I'm working on a service that needs to handle this. Thanks in advance! I'm coming from a different tech stack and learning C++. Any feedback is welcome! I'd love to hear your thoughts on this. I'd love to hear your thoughts on this.