Lumiera 0.pre.04~rc.1
»edit your freedom«
Loading...
Searching...
No Matches
optional-ref.hpp
Go to the documentation of this file.
1/*
2 OPTIONAL-REF.hpp - optional and switchable reference
3
4 Copyright (C)
5 2010, Hermann Vosseler <Ichthyostega@web.de>
6
7  **Lumiera** is free software; you can redistribute it and/or modify it
8  under the terms of the GNU General Public License as published by the
9  Free Software Foundation; either version 2 of the License, or (at your
10  option) any later version. See the file COPYING for further details.
11
12*/
13
14
22#ifndef LIB_OPTIONAL_REF_H
23#define LIB_OPTIONAL_REF_H
24
25#include "lib/error.hpp"
26
27
28namespace lib {
29
30 using LERR_(BOTTOM_VALUE);
31
32
33
34
35
51 template<typename T>
53 {
54 T* ref_;
55
56
57 public:
59 : ref_(0)
60 { }
61
63 {
64 clear();
65 }
66
67 // using default copy operations...
68
69 explicit
70 OptionalRef(T& target)
71 : ref_(&target)
72 { }
73
74 explicit operator bool() const { return isValid(); }
75
76
77 T&
79 {
80 if (!isValid())
81 throw lumiera::error::Logic ("access to this object is (not/yet) enabled"
82 , LERR_(BOTTOM_VALUE));
83 return *ref_;
84 }
85
86
87 /* === mutations ===*/
88
89 void
90 link_to (T& target)
91 {
92 ref_ = &target;
93 }
94
95 void
97 {
98 ref_ = 0;
99 }
100
101
102 /* === comparison and diagnostics === */
103
104 bool
105 isValid() const
106 {
107 return bool(ref_);
108 }
109
110 bool
111 points_to (T const& target) const
112 {
113 return isValid()
114 and ref_ == &target;
115 }
116
117 friend bool
118 operator== (OptionalRef const& r1, OptionalRef const& r2)
119 {
120 return r1.ref_ == r2.ref_;
121 }
122 friend bool
123 operator!= (OptionalRef const& r1, OptionalRef const& r2)
124 {
125 return r1.ref_ != r2.ref_;
126 }
127
128 // mixed comparisons
129 friend bool
130 operator== (OptionalRef const& ref, T const& otherTarget)
131 {
132 return ref() == otherTarget;
133 }
134
135 friend bool operator== (T const& otherTarget, OptionalRef const& ref) { return ref == otherTarget; }
136 friend bool operator!= (T const& otherTarget, OptionalRef const& ref) { return !(ref == otherTarget); }
137 friend bool operator!= (OptionalRef const& ref, T const& otherTarget) { return !(ref == otherTarget); }
138 };
139
140
141 template<typename T>
142 OptionalRef<T>
143 optionalRefTo (T& target)
144 {
145 return OptionalRef<T> (target);
146 }
147
148
149
150} // namespace lib
151#endif
Optional or switchable link to an existing object.
T & operator()() const
bool isValid() const
friend bool operator==(OptionalRef const &r1, OptionalRef const &r2)
bool points_to(T const &target) const
OptionalRef(T &target)
friend bool operator!=(OptionalRef const &r1, OptionalRef const &r2)
void link_to(T &target)
Lumiera error handling (C++ interface).
#define LERR_(_NAME_)
Definition error.hpp:45
Implementation namespace for support and library code.
OptionalRef< T > optionalRefTo(T &target)
LumieraError< LERR_(LOGIC)> Logic
Definition error.hpp:207