cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

Best practices: accessing the data in a `std::variant`

Open jomiller opened this issue 7 months ago • 1 comments

Channel

C++Weekly

Topics

There are several ways of accessing the data in a std::variant, including std::visit, std::get and std::get_if. What are the best practices for using each of these functions? Does the answer depend on the number of alternatives in the std::variant? For example, if a std::variant has only two alternatives (and it will never have more), are either of the following patterns ever better than using std::visit?

std::variant<int, std::string> myVariant = ...;
if (auto* intValue = std::get_if<int>(&myVariant); intValue)
{
    twiddle(*intValue);
}
else
{
    frobnicate(std::get<std::string>(myVariant));
}
std::variant<int, std::string> myVariant = ...;
if (std::holds_alternative<int>(myVariant))
{
    twiddle(std::get<int>(myVariant));
}
else
{
    frobnicate(std::get<std::string>(myVariant));
}

Length

5-10 minutes

jomiller avatar May 23 '25 14:05 jomiller

I'd personally vote for always using std::visit (or the new .visit) unless you're just testing something quickly. Using visit is more verbose but there's a benefit to having to always handle all cases: it helps you catch forgotten places that need changing when you update the variant types, especially when you add new ones. For this reason you should also avoid using catch-all overloads in the visitor functor, since that completely circumvents the usefulness.

LB-- avatar May 26 '25 19:05 LB--