| 1 | // ============================================================ // |
|---|
| 2 | // // |
|---|
| 3 | // File : lazy.h // |
|---|
| 4 | // Purpose : helpers for lazy evaluation // |
|---|
| 5 | // // |
|---|
| 6 | // Coded by Ralf Westram (coder@reallysoft.de) in July 2017 // |
|---|
| 7 | // http://www.arb-home.de/ // |
|---|
| 8 | // // |
|---|
| 9 | // ============================================================ // |
|---|
| 10 | |
|---|
| 11 | #ifndef LAZY_H |
|---|
| 12 | #define LAZY_H |
|---|
| 13 | |
|---|
| 14 | #ifndef ARB_ASSERT_H |
|---|
| 15 | #include <arb_assert.h> |
|---|
| 16 | #endif |
|---|
| 17 | #ifndef _GLIBCXX_CMATH |
|---|
| 18 | #include <cmath> |
|---|
| 19 | #endif |
|---|
| 20 | #ifndef ARBTOOLS_H |
|---|
| 21 | #include "arbtools.h" |
|---|
| 22 | #endif |
|---|
| 23 | |
|---|
| 24 | |
|---|
| 25 | template<typename T, T UNDEFINED> |
|---|
| 26 | class Lazy { |
|---|
| 27 | /*! defines a type with an explicit UNDEFINED value. |
|---|
| 28 | * Default ctor uses UNDEFINED value. |
|---|
| 29 | * Allows to test whether instance has been assigned a value. |
|---|
| 30 | * Fails assertion if UNDEFINED value is retrieved or assigned. |
|---|
| 31 | */ |
|---|
| 32 | T val; |
|---|
| 33 | public: |
|---|
| 34 | Lazy() : val(UNDEFINED) {} |
|---|
| 35 | explicit Lazy(T init) : val(init) { arb_assert(has_value()); } // use to assign new value |
|---|
| 36 | |
|---|
| 37 | bool needs_eval() const { return val == UNDEFINED; } |
|---|
| 38 | bool has_value() const { return !needs_eval(); } |
|---|
| 39 | |
|---|
| 40 | operator T() const { // @@@ return const&? |
|---|
| 41 | arb_assert(has_value()); // no value assigned |
|---|
| 42 | return val; |
|---|
| 43 | } |
|---|
| 44 | const Lazy& operator = (const T& newval) { |
|---|
| 45 | val = newval; |
|---|
| 46 | arb_assert(has_value()); |
|---|
| 47 | return *this; |
|---|
| 48 | } |
|---|
| 49 | }; |
|---|
| 50 | |
|---|
| 51 | template<typename T> |
|---|
| 52 | class LazyFloat { |
|---|
| 53 | /*! same as Lazy for floating point (uses NAN as UNDEFINED value) |
|---|
| 54 | */ |
|---|
| 55 | T val; |
|---|
| 56 | |
|---|
| 57 | public: |
|---|
| 58 | LazyFloat() : val(NAN) {} |
|---|
| 59 | explicit LazyFloat(T init) : val(init) { arb_assert(has_value()); } // use to assign new value |
|---|
| 60 | |
|---|
| 61 | bool needs_eval() const { return is_nan(val); } |
|---|
| 62 | bool has_value() const { return !needs_eval(); } |
|---|
| 63 | |
|---|
| 64 | operator T() const { // @@@ return const&? |
|---|
| 65 | arb_assert(has_value()); // no value assigned |
|---|
| 66 | return val; |
|---|
| 67 | } |
|---|
| 68 | const LazyFloat& operator = (const T& newval) { |
|---|
| 69 | val = newval; |
|---|
| 70 | arb_assert(has_value()); |
|---|
| 71 | return *this; |
|---|
| 72 | } |
|---|
| 73 | }; |
|---|
| 74 | |
|---|
| 75 | #else |
|---|
| 76 | #error lazy.h included twice |
|---|
| 77 | #endif // LAZY_H |
|---|