Search⌘ K

Visiting Multiple Variants

Explore how to visit multiple std::variant objects simultaneously using std::visit in C++17. Understand the necessity of implementing function overloads for all type combinations and how generic lambdas simplify handling unlisted cases. This lesson also covers comparison, movement, and hashing of variants to deepen your mastery of std::variant operations.

Variants And Overloading

std::visit allows you not only to visit one variant but many in the same call. However, it’s essential to know that with multiple variants, you have to implement function overloads taking as many arguments as the number of input variants. And you have to provide all the possible combination of types.

For example, for the following:

C++
std::variant<int, float, char> v1 { 's' };
std::variant<int, float, char> v2 { 10 };

You have to provide 9 function overloads if you call std::visit on the two ...