Tag: C++, std::variant, std::visit

  • Using std::visit with Variant Types in C++17

    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 var = “Hello”;
    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.