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;
}
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?