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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?