CodexBloom - Programming Q&A Platform

Unexpected Behavior with std::variant and std::visit in C++20

๐Ÿ‘€ Views: 3 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-06
c++20 std-variant std-visit C++

I'm stuck on something that should probably be simple. I tried several approaches but none seem to work. I'm facing an issue with `std::variant` and `std::visit` in C++20. I have a variant that can hold either an `int` or a `std::string`, and I'm trying to use `std::visit` to process it. However, I'm encountering a strange behavior where my `std::visit` function seems to ignore the `int` case completely and always falls back to the `std::string` case, even when the variant is initialized with an `int`. Hereโ€™s a simplified version of my code: ```cpp #include <iostream> #include <variant> #include <string> int main() { std::variant<int, std::string> myVar; myVar = 42; // setting the variant to hold an int auto visitor = [](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, int>) { std::cout << "Int value: " << arg << '\n'; } else if constexpr (std::is_same_v<T, std::string>) { std::cout << "String value: " << arg << '\n'; } }; std::visit(visitor, myVar); return 0; } ``` When I run this code, I expect to see "Int value: 42" printed out, but instead, thereโ€™s no output whatsoever. I've also tried printing the type of `myVar` before visiting it, and it confirms that the variant indeed holds an `int`. Iโ€™ve ensured that I included the right headers and am using a compliant C++20 compiler (g++ version 10.2). Could there be something Iโ€™m missing in how `std::visit` works with `std::variant`, or am I possibly overlooking a subtle detail? Any insights would be greatly appreciated! My development environment is Linux. The project is a REST API built with C++. Could someone point me to the right documentation? Thanks for any help you can provide!