Cosmetics.
[LibreOffice.git] / include / o3tl / lazy_update.hxx
blob951a9bb7bdc2e10c86f0cd94f43c65a976452eb8
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #ifndef INCLUDED_O3TL_LAZY_UPDATE_HXX
21 #define INCLUDED_O3TL_LAZY_UPDATE_HXX
23 #include <utility>
25 namespace o3tl
27 /** Update output object lazily
29 This template collects data in input type, and updates the
30 output type with the given update functor, but only if the
31 output is requested. Useful if updating is expensive, or input
32 changes frequently, but output is only comparatively seldom
33 used.
35 @example
36 <pre>
37 LazyUpdate<InType,OutType,decltype(F)> myValue(F);
38 *myValue = newInput;
39 myValue->updateInput( this, that, those );
41 output( *myValue );
42 </pre>
44 <pre>
45 output( myValue.getOutValue() );
46 </pre>
47 if the compiler does not recognize the const context.
49 template<typename In, typename Out, typename Func> class LazyUpdate {
50 public:
51 LazyUpdate(Func const & func): func_(func), input_(), dirty_(true) {}
53 In const & getInValue() const { return input_; }
55 Out const & getOutValue() const { return update(); }
57 In & operator *() {
58 dirty_ = true;
59 return input_;
62 In * operator ->() {
63 dirty_ = true;
64 return &input_;
67 Out const & operator *() const { return update(); }
69 Out const * operator ->() const { return &update(); }
71 private:
72 Out const & update() const {
73 if (dirty_) {
74 output_ = func_(input_);
75 dirty_ = false;
77 return output_;
80 Func const func_;
81 In input_;
82 mutable Out output_;
83 mutable bool dirty_;
87 #endif
89 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */