Maybe Result
 All Classes Functions
example.cpp
1 #include <maybe/result.hpp>
2 #include <vector>
3 
4 using maybe::result;
5 using namespace std;
6 
7 /**
8  * Error type.
9  */
10 enum class LoadError {
11  FileNotFound,
12 };
13 
14 /**
15  * Example function that returns a successful result or error depending on param.
16  */
17 result<vector<string>, LoadError> load_names(bool return_successfully)
18 {
19  if (return_successfully) {
20  return result<vector<string>, LoadError>::ok({"Bob", "Alice"});
21  } else {
22  return result<vector<string>, LoadError>::err(LoadError::FileNotFound);
23  }
24 }
25 
26 /**
27  * Chain both functions and merge results into one.
28  *
29  * If `return_success_from_first` is false, the fist function will fail.
30  */
31 result<size_t, string> run(bool return_success_from_first)
32 {
33  return load_names(success) // function will fail depending on flag
34  // run this if previous succeeds
35  .and_then([](auto prev_names) {
36  // combine results of both
37  return load_names(true).map([prev_names](auto more_names) {
38  vector<string> all;
39  copy(prev_names.begin(), prev_names.end(), back_inserter(all));
40  copy(more_names.begin(), more_names.end(), back_inserter(all));
41  return all;
42  });
43  })
44  // change error from LoadError to string
45  .map_err([](auto err) {
46  if (err == LoadError::FileNotFound) {
47  return string("file not found");
48  }
49  return string("other error");
50  })
51  // map result value to the number of elements in vector
52  .map([](vector<string> results) { return results.size(); });
53 }
54 
55 void main() {
56  auto success_result = run(true);
57 
58  assert(success_result);
59  assert(success_result.ok_value() == 4);
60 
61  auto error_result = run(false);
62 
63  assert(!error_result);
64  assert(error_result.err_value() == "file not found");
65 }
STL namespace.