CodexBloom - Programming Q&A Platform

C++17 std::variant not producing expected output with user-defined types

๐Ÿ‘€ Views: 60 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-01
c++17 std-variant custom-types cpp

I can't seem to get I need some guidance on This might be a silly question, but This might be a silly question, but I'm encountering an issue using `std::variant` with my custom types in C++17... I have defined a variant type that includes a couple of structs, but when I try to access the value of the variant, I'm getting unexpected results. Hereโ€™s a simplified version of my code: ```cpp #include <variant> #include <iostream> #include <string> struct Foo { int a; }; struct Bar { std::string b; }; using MyVariant = std::variant<Foo, Bar>; void processVariant(MyVariant v) { if (std::holds_alternative<Foo>(v)) { Foo f = std::get<Foo>(v); std::cout << "Foo: " << f.a << std::endl; } else if (std::holds_alternative<Bar>(v)) { Bar b = std::get<Bar>(v); std::cout << "Bar: " << b.b << std::endl; } } int main() { MyVariant v = Foo{42}; processVariant(v); v = Bar{"Hello"}; processVariant(v); return 0; } ``` When I run this, I expect it to first print `Foo: 42` and then `Bar: Hello`. However, I'm seeing output like `Foo: -2137454088` for the first call, which is clearly incorrect. I suspect it might be a problem with how I am accessing the variant, but I've double-checked the types and the way Iโ€™m using `std::get`. I also tried using `std::visit` instead of `std::holds_alternative` and `std::get`, but I faced similar issues. Hereโ€™s the code with `std::visit`: ```cpp #include <variant> #include <iostream> #include <string> struct Foo { int a; }; struct Bar { std::string b; }; using MyVariant = std::variant<Foo, Bar>; struct Visitor { void operator()(Foo f) { std::cout << "Foo: " << f.a << std::endl; } void operator()(Bar b) { std::cout << "Bar: " << b.b << std::endl; } }; int main() { MyVariant v = Foo{42}; std::visit(Visitor{}, v); v = Bar{"Hello"}; std::visit(Visitor{}, v); return 0; } ``` This also led to the same issue with incorrect output. Iโ€™d appreciate any insights or suggestions on what I might be missing. Is there a particular aspect of `std::variant` with user-defined types that needs special attention? Iโ€™m using GCC 9.3.0 for compiling. My development environment is Windows. This is part of a larger API I'm building. Any help would be greatly appreciated! I've been using Cpp for about a year now. What's the correct way to implement this? Thanks for any help you can provide! For reference, this is a production mobile app. Any examples would be super helpful. Any examples would be super helpful.