| 36 | { |
| 37 | template < typename ReturnType > |
| 38 | class CachedValue |
| 39 | { |
| 40 | public: |
| 41 | template < typename... Args > |
| 42 | using CachedFunction = |
| 43 | typename std::add_pointer< ReturnType( Args... ) >::type; |
| 44 | |
| 45 | CachedValue() = default; |
| 46 | CachedValue( const CachedValue& other ) |
| 47 | { |
| 48 | value_ = other.value_; |
| 49 | computed_ = other.computed_.load(); |
| 50 | } |
| 51 | CachedValue( CachedValue&& other ) noexcept |
| 52 | { |
| 53 | value_ = std::move( other.value_ ); |
| 54 | computed_ = other.computed_.load(); |
| 55 | } |
| 56 | |
| 57 | CachedValue& operator=( const CachedValue& other ) |
| 58 | { |
| 59 | value_ = other.value_; |
| 60 | computed_ = other.computed_.load(); |
| 61 | return *this; |
| 62 | } |
| 63 | |
| 64 | CachedValue& operator=( CachedValue&& other ) noexcept |
| 65 | { |
| 66 | value_ = std::move( other.value_ ); |
| 67 | computed_ = other.computed_.load(); |
| 68 | return *this; |
| 69 | } |
| 70 | |
| 71 | template < typename... Args > |
| 72 | const ReturnType& operator()( |
| 73 | CachedFunction< Args... > computer, Args&&... args ) const |
| 74 | { |
| 75 | if( !computed_ ) |
| 76 | { |
| 77 | absl::MutexLock lock{ mutex_ }; |
| 78 | if( !computed_ ) |
| 79 | { |
| 80 | value_ = computer( std::forward< Args >( args )... ); |
| 81 | computed_ = true; |
| 82 | } |
| 83 | } |
| 84 | return value_; |
| 85 | } |
| 86 | |
| 87 | bool operator!=( const CachedValue& other ) const |
| 88 | { |
| 89 | if( computed() && other.computed() ) |
| 90 | { |
| 91 | return value() != other.value(); |
| 92 | } |
| 93 | return false; |
| 94 | } |
| 95 | |