| Line | |
|---|
| 1 | // ========================================================= // |
|---|
| 2 | // // |
|---|
| 3 | // File : ErrorOrType.h // |
|---|
| 4 | // Purpose : provide "hybrid" result type // |
|---|
| 5 | // // |
|---|
| 6 | // Coded by Ralf Westram (coder@reallysoft.de) in Apr 19 // |
|---|
| 7 | // http://www.arb-home.de/ // |
|---|
| 8 | // // |
|---|
| 9 | // ========================================================= // |
|---|
| 10 | |
|---|
| 11 | #ifndef ERRORORTYPE_H |
|---|
| 12 | #define ERRORORTYPE_H |
|---|
| 13 | |
|---|
| 14 | #ifndef ARB_ERROR_H |
|---|
| 15 | #include "arb_error.h" |
|---|
| 16 | #endif |
|---|
| 17 | |
|---|
| 18 | template<typename TYPE> |
|---|
| 19 | class ErrorOr { |
|---|
| 20 | /*! "hybrid" result type: is either an error or a value. |
|---|
| 21 | * Note: TYPE has to be copyable! |
|---|
| 22 | * You have to use getError() or getValue() before an instance is destroyed! |
|---|
| 23 | */ |
|---|
| 24 | |
|---|
| 25 | // unittest at ../SL/HEADERTESTS/test_arb_error.cxx@TEST_ErrorOr |
|---|
| 26 | ARB_ERROR error; |
|---|
| 27 | TYPE value; |
|---|
| 28 | |
|---|
| 29 | #if defined(ASSERTION_USED) |
|---|
| 30 | mutable bool checked; |
|---|
| 31 | #endif |
|---|
| 32 | |
|---|
| 33 | void mark_checked() const { |
|---|
| 34 | #if defined(ASSERTION_USED) |
|---|
| 35 | checked = true; |
|---|
| 36 | #endif |
|---|
| 37 | } |
|---|
| 38 | void expect_checked() const { arb_assert(checked); } |
|---|
| 39 | |
|---|
| 40 | public: |
|---|
| 41 | ErrorOr(ARB_ERROR err, const TYPE& t) : |
|---|
| 42 | error(err), |
|---|
| 43 | value(t) |
|---|
| 44 | #if defined(ASSERTION_USED) |
|---|
| 45 | , checked(false) |
|---|
| 46 | #endif |
|---|
| 47 | { |
|---|
| 48 | } |
|---|
| 49 | |
|---|
| 50 | bool hasError() const { mark_checked(); return error; } |
|---|
| 51 | bool hasValue() const { return !hasError(); } |
|---|
| 52 | |
|---|
| 53 | ARB_ERROR getError() const { // may only be used once! |
|---|
| 54 | expect_checked(); |
|---|
| 55 | arb_assert(hasError()); |
|---|
| 56 | return error; |
|---|
| 57 | } |
|---|
| 58 | TYPE getValue() const { // may only be used once! |
|---|
| 59 | expect_checked(); |
|---|
| 60 | arb_assert(hasValue()); |
|---|
| 61 | error.expect_no_error(); |
|---|
| 62 | return value; |
|---|
| 63 | } |
|---|
| 64 | }; |
|---|
| 65 | |
|---|
| 66 | #else |
|---|
| 67 | #error ErrorOrType.h included twice |
|---|
| 68 | #endif // ERRORORTYPE_H |
|---|
Note: See
TracBrowser
for help on using the repository browser.