How do I pattern match (std::visit) std::expected (when available) in C++?

Pattern matching with std::expected using std::visit is a powerful way to handle various outcomes of operations in modern C++. With the release of C++20, std::expected provides a way to represent values which may either be a valid result or an error. Below is an example of how to utilize pattern matching effectively with std::expected and std::visit.

Here’s a simple example of how to do that:

#include <variant> #include <expected> #include <iostream> // Define a simple expected type using MyExpected = std::expected<int, std::string>; // Sample function which returns std::expected MyExpected divide(int numerator, int denominator) { if (denominator == 0) return std::unexpected("Division by zero"); return numerator / denominator; } int main() { auto result = divide(10, 0); // Use std::visit to pattern match on std::expected std::visit([](auto&& arg) { using T = std::decay_t<decltype(arg)>; if constexpr (std::is_same_v<T, int>) { std::cout << "Result: " << arg << std::endl; } else { std::cout << "Error: " << arg << std::endl; } }, result); return 0; }

C++ std::expected std::visit error handling pattern matching modern C++