source: branches/help/TEMPLATES/ErrorOrType.h

Last change on this file was 18634, checked in by westram, 4 years ago
File size: 1.8 KB
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
18template<typename TYPE>
19class 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    ARB_ERROR error;
25    TYPE      value;
26
27#if defined(ASSERTION_USED)
28    mutable bool checked;
29#endif
30
31    void mark_checked() const {
32#if defined(ASSERTION_USED)
33        checked = true;
34#endif
35    }
36    void expect_checked() const { arb_assert(checked); }
37
38public:
39    ErrorOr(ARB_ERROR err, const TYPE& t) :
40        error(err),
41        value(t)
42#if defined(ASSERTION_USED)
43        , checked(false)
44#endif
45    {
46    }
47
48    bool hasError() const { mark_checked(); return error; }
49    bool hasValue() const { return !hasError(); }
50
51    ARB_ERROR getError() const { // may only be used once!
52        expect_checked();
53        arb_assert(hasError());
54        return error;
55    }
56    TYPE getValue() const { // may only be used once!
57        expect_checked();
58        arb_assert(hasValue());
59        error.expect_no_error();
60        return value;
61    }
62};
63
64#else
65#error ErrorOrType.h included twice
66#endif // ERRORORTYPE_H
Note: See TracBrowser for help on using the repository browser.