42 "Path cannot be empty",
47 std::ifstream file(path);
48 if (!file.is_open()) {
51 "File not found: " + path,
56 std::string content((std::istreambuf_iterator<char>(file)),
57 std::istreambuf_iterator<char>());
64 auto pos = expr.find(
'/');
65 if (pos == std::string::npos) {
68 "Invalid expression format",
74 int a = std::stoi(expr.substr(0, pos));
75 int b = std::stoi(expr.substr(pos + 1));
77 }
catch (
const std::exception& e) {
80 std::string(
"Parse error: ") + e.what(),
87 std::cout <<
"=== Result Pattern Examples ===\n\n";
90 std::cout <<
"1. Basic division:\n";
91 auto result1 =
divide(10, 2);
92 if (result1.is_ok()) {
93 std::cout <<
" 10 / 2 = " << result1.value() <<
"\n";
96 auto result2 =
divide(10, 0);
97 if (result2.is_err()) {
99 std::cout <<
" Error: " <<
err.message
100 <<
" (code: " <<
err.code <<
")\n";
104 std::cout <<
"\n2. Using value_or:\n";
105 auto value =
divide(10, 0).unwrap_or(-1);
106 std::cout <<
" 10 / 0 with default -1 = " << value <<
"\n";
109 std::cout <<
"\n3. Pattern matching:\n";
111 if (result3.is_ok()) {
112 std::cout <<
" Success: " << result3.unwrap() <<
"\n";
114 std::cout <<
" Failed: " << result3.error().message <<
"\n";
118 std::cout <<
"\n4. Monadic operations:\n";
119 auto result4 =
divide(100, 5);
120 auto doubled = result4.map([](
int x) {
return x * 2; });
121 if (doubled.is_ok()) {
122 std::cout <<
" (100 / 5) * 2 = " << doubled.value() <<
"\n";
126 std::cout <<
"\n5. Chaining operations:\n";
127 auto chain_result =
divide(50, 5)
128 .and_then([](
int x) {
return divide(x, 2); });
129 if (chain_result.is_ok()) {
130 std::cout <<
" (50 / 5) / 2 = " << chain_result.value() <<
"\n";
134 std::cout <<
"\n6. Error recovery:\n";
135 auto recovered =
divide(10, 0)
137 std::cout <<
" 10 / 0 with recovery = " << recovered.value() <<
"\n";
140 std::cout <<
"\n7. Exception wrapping:\n";
142 throw std::runtime_error(
"Something went wrong");
144 },
"example_module");
146 if (wrapped.is_err()) {
148 std::cout <<
" Caught exception: " <<
err.message <<
"\n";
151 std::cout <<
"\n=== Examples completed ===\n";
Result type for error handling with member function support.
const error_info & error() const
Get error reference.
constexpr int INVALID_ARGUMENT
Result< T > make_error(int code, const std::string &message, const std::string &module="")
Create an error result with code and message.
Result< T > try_catch(F &&func, const std::string &module="")
Convert exception to Result with automatic error code mapping.
VoidResult err(const error_info &error)
Factory function to create error VoidResult.
VoidResult ok()
Create a successful void result.
Umbrella header for Result<T> type and related utilities.
Result< int > parse_and_compute(const std::string &expr)
Result< std::string > read_file(const std::string &path)
Result< int > divide(int a, int b)
Standard error information used by Result<T>.