4 * This file is part of LyX, the document processor.
5 * Licence details can be found in the file COPYING.
7 * \author Guillaume Munch
9 * Full author contact details are available in file CREDITS.
18 #include <type_traits>
23 * Cache<Key, T> implements a cache where objects are stored by copy.
25 * This is a wrapper for QCache. See the documentation of QCache:
26 * <https://doc.qt.io/qt-5/qcache.html>.
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.
32 * Use this rather than QCache directly, to avoid naked pointers.
34 template <class Key, class Val>
35 class Cache : private QCache<Key, Val> {
36 static_assert(std::is_copy_constructible<Val>::value,
37 "lyx::Cache only stores copyable objects!");
38 static_assert(std::is_default_constructible<Val>::value,
39 "lyx::Cache only stores default-constructible objects!");
40 using Q = QCache<Key, Val>;
44 Cache(int max_cost = 100) : Q(max_cost) {}
46 bool insert(Key const & key, Val object, int cost = 1)
48 return Q::insert(key, new Val(std::move(object)), cost);
50 // Returns the default value (e.g. null pointer) if not found in the
51 // cache. If this is not convenient for your class Val, check if it exists
52 // beforehand with Cache::contains.
53 Val object(Key const & key) const
55 if (Val * obj = Q::object(key))
59 /// Synonymous for object, same remark as above.
60 Val operator[](Key const & key) const { return object(key); }
61 /// Everything from QCache except QCache::take.
67 bool empty() const { return Q::isEmpty(); }
68 std::list<Key> keys() { return Q::keys().toStdList(); }
69 int max_cost() const { return Q::maxCost(); }
70 void set_max_cost(int cost) { Q::setMaxCost(cost); }
71 int total_cost() const { return Q::totalCost(); }