C++17 introduced `std::variant` for type-safe unions. You can hold multiple types in a single variable. `std::visit` allows you to apply a function to the active type. This simplifies working with variants. Here’s an example:
“`cpp
#include
#include
using namespace std;
void visitor(int i) { cout << "Integer: " << i << endl; }
void visitor(const string& s) { cout << "String: " << s << endl; }
int main() {
variant
visit(visitor, var); // Outputs String: Hello
return 0;
}
“`
In this code, `std::visit` calls the appropriate visitor function. This approach enhances code clarity and safety.
Leave a Reply