C/C++ Arena

Step 2 of 6

std::variant and std::visit

std::variant<A, B, C> holds exactly one of several types, and knows which. It's a type-safe union.

std::variant<int, std::string> v = 5;
v = "hello";                               // now holds a string
std::holds_alternative<std::string>(v);    // true
std::get<std::string>(v);                  // "hello"

std::visit calls a function with whatever is inside. A lambda with an auto parameter handles every type:

std::visit([](const auto& x) { std::cout << x; }, v);

Your turn: an Event is either a Kill{attacker, victim}, a Plant{site} or a RoundEnd{winner}. Write std::string describe(const Event& e) returning "A killed B", "bomb planted at X" or "round to W". Use std::holds_alternative/std::get, or std::get_if.

Previous: std::optional Next: std::string_view