-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy path003_error_std_error_condition.cpp
More file actions
63 lines (52 loc) · 1.75 KB
/
003_error_std_error_condition.cpp
File metadata and controls
63 lines (52 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
enum class MyErrorCondition {
kChenggong,
kWangluoCuowu,
kQingqiuCuowu,
kFuwuqiCuowu,
};
class MyErrorCategory: public std::error_category
{
public:
static MyErrorCategory const& instance() {
static MyErrorCategory instance;
return instance;
}
char const *name() const noexcept override {
return "MyErrorCategory";
}
std::string message(int code) const override {
return "Message";
}
bool equivalent(std::error_code const& code, int condition) const noexcept override {
auto const& yourErrorCodeCategory = std::error_code(YourErrorCode{}).category();
if (code.category() == yourErrorCodeCategory) {
switch (static_cast<MyErrorCondition>(condition)) {
case MyErrorCondition::kChenggong:
return code == YourErrorCode::kSuccess;
case MyErrorCondition::kWangluoCuowu:
return code == YourErrorCode::kNetworkError;
case MyErrorCondition::kQingqiuCuowu:
return code == YourErrorCode::kBadRequest;
case MyErrorCondition::kFuwuqiCuowu:
return code == YourErrorCode::kServerError;
}
}
return false;
}
};
// error_condition 同样需要特化模版启动重载
namespace std {
template<>
struct is_error_condition_enum<MyErrorCondition>: true_type {};
}
// error_condition 同样可以通过工厂函数构造
std::error_condition make_error_condition(MyErrorCondition code)
{
return {static_cast<int>(code), MyErrorCategory::instance()};
}
int main()
{
std::error_code code = YourErrorCode::kNetworkError;
std::error_condition condition = MyErrorCondition::kWangluoCuowu;
std::cout << (code == condition) << '\n';
}