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 #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>;
43 typedef QCache<Key, Val> Q;
48 Cache(int max_cost = 100) : Q(max_cost) {}
50 bool insert(Key const & key, Val object, int cost = 1)
52 return Q::insert(key, new Val(std::move(object)), cost);
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
59 if (Val * obj = Q::object(key))
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.
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(); }