2 // Copyright 2013 Francisco Jerez
4 // Permission is hereby granted, free of charge, to any person obtaining a
5 // copy of this software and associated documentation files (the "Software"),
6 // to deal in the Software without restriction, including without limitation
7 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 // and/or sell copies of the Software, and to permit persons to whom the
9 // Software is furnished to do so, subject to the following conditions:
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 // OTHER DEALINGS IN THE SOFTWARE.
23 #ifndef CLOVER_UTIL_LAZY_HPP
24 #define CLOVER_UTIL_LAZY_HPP
26 #include <type_traits>
43 operator T() const = 0;
46 template<typename T, typename F>
47 class deferred_lazy : public basic_lazy<T> {
50 deferred_lazy(G &&f) : f(new F(std::forward<G>(f))) {
53 virtual basic_lazy<T> *
55 return new deferred_lazy(*this);
68 mutable std::shared_ptr<F> f;
73 class strict_lazy : public basic_lazy<T> {
76 strict_lazy(S &&x) : x(std::forward<S>(x)) {
79 virtual basic_lazy<T> *
81 return new strict_lazy(*this);
94 /// Object that represents a value of type \a T that is calculated
95 /// lazily as soon as it is required.
100 class undefined_error : std::logic_error {
102 undefined_error() : std::logic_error("") {
107 /// Initialize to some fixed value \a x which isn't calculated
110 lazy(T x) : obj(new detail::strict_lazy<T>(x)) {
114 /// Initialize by providing a functor \a f that will calculate
115 /// the value on-demand.
118 lazy(F &&f) : obj(new detail::deferred_lazy<
119 T, typename std::remove_reference<F>::type
120 >(std::forward<F>(f))) {
124 /// Initialize to undefined.
127 throw undefined_error();
132 lazy(const lazy &other) : obj(obj->clone()) {
135 lazy(lazy &&other) : obj(NULL) {
136 std::swap(obj, other.obj);
144 operator=(lazy other) {
145 std::swap(obj, other.obj);
150 /// Evaluate the value.
157 detail::basic_lazy<T> *obj;