How do I use expected-like types for error handling?

Using expected-like types in C++ provides a robust way to handle errors while maintaining type safety. This approach allows developers to return either a value or an error without resorting to exceptions or error codes, leading to clearer and more maintainable code.
C++, error handling, expected types, type safety, software development, programming practices
// Example of expected-like types in C++ #include <iostream> #include <variant> #include <string> template <typename T, typename E> class Expected { public: Expected(T value) : result(value), is_error(false) {} Expected(E error) : error_value(error), is_error(true) {} bool isError() const { return is_error; } T value() const { return result; } E error() const { return error_value; } private: T result; E error_value; bool is_error; }; Expected<int, std::string> divide(int numerator, int denominator) { if (denominator == 0) { return Expected<int, std::string>("Division by zero error"); } return Expected<int, std::string>(numerator / denominator); } int main() { auto result = divide(10, 0); if (result.isError()) { std::cout << "Error: " << result.error() << std::endl; } else { std::cout << "Result: " << result.value() << std::endl; } return 0; }

C++ error handling expected types type safety software development programming practices