Debian Codegraph @

yo/advancedtemplates/examples/errcode/main.cc

raw
1 //#define XERR
2 #include "main.ih"
3
4 void show(std::error_category &cat)
5 {
6 std::cerr << cat.name() << '\n'; // show the name of the category
7 }
8
9 int main(int argc, char **argv)
10 try
11 {
12 Category &cat = Category::instance();
13
14 cout << cat.name() << '\n'; // show the name of the category
15 show(cat); // same, with overridden name()
16
17 error_code ec = CatErr::Err2; // initialize an error_code
18 ec = CatErr::Err2; // same, direct assignment
19
20 // same, using assign()
21 ec.assign(static_cast<int>(CatErr::Err2), cat);
22
23 cout <<
24 "ec == Err2 ? " << (ec == CatErr::Err2) << "\n"
25 "ec == Err1 ? " << (ec == CatErr::Err1) << "\n"
26 "ec == Cond1 ? " << (ec == Cond::Cond1) << "\n"
27 "ec == Cond2 ? " << (ec == Cond::Cond2) << "\n"
28 "ec == Cond3 ? " << (ec == Cond::Cond3) << "\n"
29 "ec == Cond ? " << (ec == Cond{}) << "\n"
30 "ec == errc ? " << (ec == errc::not_enough_memory) << "\n"
31 // WC "ec == 1 ? " << (ec == 1) << "\n"
32 ;
33
34 cout << "error_code value: " << ec.value() <<
35 ", equivalent called from error_code: " <<
36 ec.category().equivalent(ec, static_cast<int>(Cond::Cond1)) <<
37 '\n';
38
39 cout << "Enum value of Cond::NoCond = " <<
40 error_condition{ Cond::NoCond }.value() << '\n';
41
42 cout << "Default Cond value: " << (int)Cond{} << '\n';
43
44 assert(ec != Cond::Cond1); // OK, current Cond value == Cond2
45 assert(ec == Cond::Cond2); // OK, current Cond value == Cond2
46 assert(ec != Cond{}); // OK,
47 assert(ec == CatErr::Err2);
48 // assert(ec == 2); // not OK: can't compare to int
49 // assert(ec == CatErr::Err1); // not OK: ec == Err2
50
51 cout << ec.category().name() << '\n'; // name via category()
52
53 // get the default error condition
54 error_condition cond = ec.default_error_condition();
55
56 error_condition nope{ 12, cat }; // validity not checked
57 cout << nope.value() << '\n'; // shows 12
58
59 cout << "Default error condition:\n"
60 " cat.: " << cond.category().name() << "\n" // the cat. name
61 " value: " << cond.value() << "\n" // CatErr's numeric value
62 " " << cond.message() << '\n'; // CatErr's name
63
64 error_condition errCond{ Cond::Cond1 };
65
66 cout << "Directly constructed error condition. Value = " <<
67 errCond.value() << ", message = " << errCond.message() << '\n';
68
69 cout << "Making error condition objects, showing their value:\n"
70 "Cond::Cond1: " << make_error_condition(Cond::Cond1).value() <<
71 "\n"
72 "Cond::Cond2: " << make_error_condition(Cond::Cond2).value() <<
73 '\n';
74 throw system_error{ ec, "For demonstration purposes" };
75 }
76 catch (std::system_error const &se)
77 {
78 std::cout << "System Error:\n"
79 " what() = " << se.what() << "\n"
80 " (error_)code = " << se.code() << '\n';
81 }
82 catch (...)
83 {
84 cout << "unexpected exception\n";
85 return 1;
86 }