CodexBloom - Programming Q&A Platform

Using std::variant with std::visit leads to advanced patterns in C++17

👀 Views: 12 💬 Answers: 1 📅 Created: 2025-08-20
c++17 std-variant std-visit C++

I've been banging my head against this for hours. I've spent hours debugging this and I'm writing unit tests and I've been struggling with this for a few days now and could really use some help... I'm having trouble with `std::variant` and `std::visit` in C++17 when I try to visit variants that include a user-defined type. The question arises when I attempt to access a member function of the stored type in my visitor, and I keep getting a compile-time behavior. Here’s a simplified version of my code: ```cpp #include <variant> #include <iostream> #include <string> struct MyType { std::string data; void print() const { std::cout << data << '\n'; } }; int main() { std::variant<int, MyType> myVariant = MyType{ "Hello, World!" }; auto visitor = [](auto&& arg) { arg.print(); // behavior here }; std::visit(visitor, myVariant); return 0; } ``` When I try to compile this, I get the following behavior: ``` behavior: ‘class MyType’ has no member named ‘print’ ``` I tried ensuring that the variant holds the correct type and that the visitor function is properly defined to handle each type. I’ve also verified that `MyType` does indeed have a `print` method. I’m wondering if I need to use `std::decay_t<decltype(arg)>` to ensure that the correct type is being deduced in the lambda. I tried modifying the visitor like this: ```cpp auto visitor = [](const auto& arg) { arg.print(); }; ``` But it doesn’t compile either, and I’m still working with the same scenario. How can I correctly access the member function of my stored type in this context? Is there a specific way to handle user-defined types within `std::variant` and `std::visit`? Any help would be appreciated! This is part of a larger application I'm building. What am I doing wrong? Any ideas what could be causing this? The project is a web app built with C++.