]> git.lyx.org Git - lyx.git/blob - src/support/Cache.h
Yet another deprecation fix (this is the last one I am aware of)
[lyx.git] / src / support / Cache.h
1 // -*- C++ -*-
2 /**
3  * \file Cache.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Guillaume Munch
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef CACHE_H
13 #define CACHE_H
14
15 #include <QCache>
16
17 #include <list>
18 #include <type_traits>
19
20 namespace lyx {
21
22 /**
23  * Cache<Key, T> implements a cache where objects are stored by copy.
24  *
25  * This is a wrapper for QCache. See the documentation of QCache:
26  * <https://doc.qt.io/qt-5/qcache.html>.
27  *
28  * It is especially useful for storing shared pointers. This turns QCache into a
29  * shared-ownership cache with no risks of dangling pointer. It is also useful
30  * for small copyable objects.
31  *
32  * Use this rather than QCache directly, to avoid naked pointers.
33  */
34 template <class Key, class Val>
35 class Cache : private QCache<Key, Val> {
36 #if !(defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 6))
37         static_assert(std::is_copy_constructible<Val>::value,
38                       "lyx::Cache only stores copyable objects!");
39         static_assert(std::is_default_constructible<Val>::value,
40                       "lyx::Cache only stores default-constructible objects!");
41         using Q = QCache<Key, Val>;
42 #else
43         typedef QCache<Key, Val> Q;
44 #endif
45
46 public:
47         ///
48         Cache(int max_cost = 100) : Q(max_cost) {}
49         ///
50         bool insert(Key const & key, Val object, int cost = 1)
51         {
52                 return Q::insert(key, new Val(std::move(object)), cost);
53         }
54         // Returns the default value (e.g. null pointer) if not found in the
55         // cache. If this is not convenient for your class Val, check if it exists
56         // beforehand with Cache::contains.
57         Val object(Key const & key) const
58         {
59                 if (Val * obj = Q::object(key))
60                         return *obj;
61                 return Val();
62         }
63         /// Synonymous for object, same remark as above.
64         Val operator[](Key const & key) const { return object(key); }
65         /// Everything from QCache except QCache::take.
66         using Q::clear;
67         using Q::contains;
68         using Q::count;
69         using Q::remove;
70         using Q::size;
71         bool empty() const { return Q::isEmpty(); }
72         std::list<Key> keys() { return Q::keys().toStdList(); }
73         int max_cost() const { return Q::maxCost(); }
74         void set_max_cost(int cost) { Q::setMaxCost(cost); }
75         int total_cost() const { return Q::totalCost(); }
76 };
77
78 } // namespace lyx
79
80 #endif