CodexBloom - Programming Q&A Platform

std::variant and std::visit causing compile-time errors with lambdas in C++20

๐Ÿ‘€ Views: 71 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-16
c++20 stdvariant stdvisit lambdas C++

I'm migrating some code and I'm working with a compile-time behavior when trying to use `std::variant` along with `std::visit` and lambdas in C++20. My goal is to hold either an `int` or a `std::string` in the variant and process them differently based on their type. Here's a simplified version of my code: ```cpp #include <iostream> #include <variant> #include <string> std::variant<int, std::string> myVariant; void processVariant() { std::visit([](auto&& arg) { std::cout << arg << '\n'; }, myVariant); } int main() { myVariant = 42; // This line works fine processVariant(); // This line causes a compile behavior return 0; } ``` However, when I compile this with g++, I get the following behavior: ``` behavior: no matching function for call to โ€˜processVariant()โ€™ ``` I have tried explicit template specialization for the lambda function, but that didn't help. I'm using g++ version 10.2.0 with the `-std=c++20` flag. The scenario seems to be related to the `std::variant` not being properly recognized in the `std::visit` context. I've also checked that both types held by `myVariant` are correctly included in the variant definition. Is there something I'm missing regarding the initialization of the variant or the way I'm trying to visit its contents? Any insights or suggestions would be greatly appreciated! I recently upgraded to C++ 3.11. Could someone point me to the right documentation?