How do I pattern match (std::visit) std::variant in C++?

In C++, you can use `std::visit` to perform pattern matching on `std::variant`. The `std::variant` is a type-safe union that can hold one of several types. `std::visit` allows you to apply a visitor function to the currently held value of the variant. This can simplify code significantly when dealing with different types contained in a variant.

Here's a brief example demonstrating how to use `std::visit` with `std::variant`:

#include <iostream> #include <variant> #include <string> // Define a variant that can hold an int, a double, or a string using MyVariant = std::variant<int, double, std::string>; // Visitor function to handle different types struct VarVisitor { void operator()(int value) const { std::cout << "Integer: " << value << std::endl; } void operator()(double value) const { std::cout << "Double: " << value << std::endl; } void operator()(const std::string &value) const { std::cout << "String: " << value << std::endl; } }; int main() { MyVariant v1 = 10; MyVariant v2 = 3.14; MyVariant v3 = "Hello, Variant!"; // Use std::visit to apply the visitor std::visit(VarVisitor{}, v1); std::visit(VarVisitor{}, v2); std::visit(VarVisitor{}, v3); return 0; }

C++ std::variant std::visit pattern matching variant type-safe union