How do I construct and use std::expected (when available) in C++?

In C++, the std::expected is a utility that represents the result of a computation that might fail, allowing developers to handle errors more gracefully. It is available in C++23 and provides a way to encapsulate both a successful value and a potential error value without resorting to exceptions.

Here's how to construct and use std::expected in your code:

#include <expected> #include <iostream> // Define a function that returns std::expected std::expected divide(int numerator, int denominator) { if (denominator == 0) { return std::unexpected("Division by zero error"); } return numerator / denominator; } int main() { auto result = divide(10, 2); if (result) { std::cout << "Result: " << *result << std::endl; } else { std::cout << "Error: " << result.error() << std::endl; } return 0; }

C++ std::expected error handling C++23 exceptions