|
1 | 1 | #include <fmt/core.h>
|
2 | 2 | #include <system_error>
|
3 | 3 | #include "tl-expected.hpp"
|
| 4 | +#include <fcntl.h> |
4 | 5 | // 今日主题:现代 C++ 中的错误处理
|
5 | 6 |
|
6 | 7 | // int : [INT_MIN, INT_MAX]
|
7 | 8 | // optional<int> : [INT_MIN, INT_MAX] | {nullopt}
|
8 | 9 | // variant<int, error_code> : [INT_MIN, INT_MAX] | {error_code}
|
9 | 10 | // expected<int, error_code> : [INT_MIN, INT_MAX] | {error_code}
|
10 | 11 |
|
| 12 | +template <> |
| 13 | +struct tl::bad_expected_access<std::error_code> : std::system_error { |
| 14 | + explicit bad_expected_access(std::error_code e) : std::system_error(std::move(e)) {} |
| 15 | +}; |
| 16 | + |
11 | 17 | namespace mybuss {
|
12 | 18 |
|
13 | 19 | enum class login_errc {
|
@@ -90,12 +96,45 @@ tl::expected<int, std::error_code> sqrfloor(int x) {
|
90 | 96 | // }
|
91 | 97 | }
|
92 | 98 |
|
93 |
| -int main() { |
94 |
| - auto ret = sqrfloor(3); |
95 |
| - if (ret.has_value()) { |
96 |
| - fmt::println("结果: {}", ret.value()); |
97 |
| - } else { |
98 |
| - fmt::println("出错: {}", ret.error().message()); |
| 99 | +tl::expected<int, std::error_code> expectedStdError(int ret) { |
| 100 | + if (ret == -1) { |
| 101 | + return tl::unexpected{std::error_code(errno, std::generic_category())}; |
| 102 | + } |
| 103 | + return ret; |
| 104 | +} |
| 105 | + |
| 106 | +int checkStdError(int ret) { |
| 107 | + if (ret == -1) { |
| 108 | + throw std::system_error(std::error_code(errno, std::system_category())); |
| 109 | + } |
| 110 | + return ret; |
| 111 | +} |
| 112 | + |
| 113 | +// tl::expected<void, std::error_code> expectedCudaError(int ret) { |
| 114 | +// if (ret != 0) { |
| 115 | +// return tl::unexpected{std::error_code(ret, cuda_category())}; |
| 116 | +// } |
| 117 | +// return {}; |
| 118 | +// } |
| 119 | + |
| 120 | +template <class T> |
| 121 | +using expected = tl::expected<T, std::error_code>; |
| 122 | + |
| 123 | +struct RAIIFile { |
| 124 | + int fd; |
| 125 | + |
| 126 | + tl::expected<size_t, std::error_code> write(std::span<const char> buf) { |
| 127 | + return expectedStdError(::write(fd, buf.data(), buf.size())); |
99 | 128 | }
|
| 129 | +}; |
| 130 | + |
| 131 | +// tl::expected<void *, std::error_code> cppCudaMalloc(size_t size) { |
| 132 | +// expectedCudaError(cudaMalloc(p)); |
| 133 | +// } |
| 134 | + |
| 135 | +int main() { |
| 136 | + RAIIFile file{expectedStdError(open("/tmp/test.log", O_WRONLY)).value()}; |
| 137 | + std::string s = "asasasas"; |
| 138 | + file.write(s).value(); |
100 | 139 | return 0;
|
101 | 140 | }
|
0 commit comments