source: tags/ms_r18q1/TEMPLATES/lazy.h

Last change on this file was 16164, checked in by westram, 7 years ago
File size: 2.2 KB
Line 
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
25template<typename T, T UNDEFINED>
26class 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;
33public:
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
51template<typename T>
52class LazyFloat {
53    /*! same as Lazy for floating point (uses NAN as UNDEFINED value)
54     */
55    T val;
56
57public:
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
Note: See TracBrowser for help on using the repository browser.