CodexBloom - Programming Q&A Platform

C++17 std::variant optimization guide as expected with custom types and visit function

πŸ‘€ Views: 16 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-23
c++17 stdvariant stdvisit customtypes C++

Does anyone know how to I've been researching this but I've been banging my head against this for hours... I'm working with an scenario with `std::variant` in C++17 where the `std::visit` function doesn't seem to properly handle my custom types. I have defined a `std::variant` that can hold either a `std::string` or a custom struct `MyData`. When I try to use `std::visit`, I receive a compilation behavior related to the visitor function. Here’s the relevant part of my code: ```cpp #include <variant> #include <string> #include <iostream> struct MyData { int id; std::string name; }; int main() { std::variant<std::string, MyData> v; v = MyData{1, "Sample"}; auto visitor = [](auto&& arg) { std::cout << arg << '\n'; // Compilation behavior here }; std::visit(visitor, v); return 0; } ``` When I try to compile this, I get the behavior: `behavior: no matching function for call to 'std::visit(...)'`. I suspect the scenario lies in how I'm trying to output the `MyData` struct. I have not defined an `operator<<` for my struct, but I thought `std::visit` would handle it as long as it can access the member variables. I've tried adding an overload for `operator<<`, but I'm not sure how to best implement it. Here's what I attempted: ```cpp #include <ostream> std::ostream& operator<<(std::ostream& os, const MyData& data) { return os << "MyData{ id: " << data.id << ", name: " << data.name << " }"; } ``` However, integrating that with the `std::visit` is still causing issues. What’s the correct way to implement this so that `std::visit` can handle both `std::string` and `MyData` correctly? Any insights on making this work would be greatly appreciated! For context: I'm using C++ on Ubuntu. What's the best practice here? Could someone point me to the right documentation? The project is a mobile app built with C++. I'm open to any suggestions. This issue appeared after updating to C++ 3.11. Am I missing something obvious? This issue appeared after updating to C++ latest. I appreciate any insights!