Mercurial > hg > svcore
comparison base/ById.h @ 1729:abd8b9673028 by-id
Experiment toward working out an id-model store
author | Chris Cannam |
---|---|
date | Thu, 20 Jun 2019 14:57:39 +0100 |
parents | |
children | 601851995f4b |
comparison
equal
deleted
inserted
replaced
1727:8efce64dd85e | 1729:abd8b9673028 |
---|---|
1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ | |
2 | |
3 /* | |
4 Sonic Visualiser | |
5 An audio file viewer and annotation editor. | |
6 Centre for Digital Music, Queen Mary, University of London. | |
7 | |
8 This program is free software; you can redistribute it and/or | |
9 modify it under the terms of the GNU General Public License as | |
10 published by the Free Software Foundation; either version 2 of the | |
11 License, or (at your option) any later version. See the file | |
12 COPYING included with this distribution for more information. | |
13 */ | |
14 | |
15 #ifndef SV_BY_ID_H | |
16 #define SV_BY_ID_H | |
17 | |
18 #include <memory> | |
19 #include <map> | |
20 | |
21 #include <QMutex> | |
22 | |
23 typedef int Id; | |
24 | |
25 class WithId | |
26 { | |
27 public: | |
28 WithId() : | |
29 m_id(getNextId()) { | |
30 } | |
31 | |
32 Id getId() const { | |
33 return m_id; | |
34 } | |
35 | |
36 private: | |
37 Id m_id; | |
38 static int getNextId(); | |
39 }; | |
40 | |
41 template <typename Item> | |
42 class ById | |
43 { | |
44 public: | |
45 void add(std::shared_ptr<Item> item) { | |
46 QMutexLocker locker(&m_mutex); | |
47 m_items[item->getId()] = item; | |
48 } | |
49 | |
50 void | |
51 release(Id id) { | |
52 QMutexLocker locker(&m_mutex); | |
53 m_items.erase(id); | |
54 } | |
55 | |
56 std::shared_ptr<Item> get(Id id) const { | |
57 QMutexLocker locker(&m_mutex); | |
58 const auto &itr = m_items.find(id); | |
59 if (itr != m_items.end()) { | |
60 return itr->second; | |
61 } else { | |
62 return std::shared_ptr<Item>(); | |
63 } | |
64 } | |
65 | |
66 template <typename Derived> | |
67 std::shared_ptr<Derived> getAs(Id id) const { | |
68 return std::dynamic_pointer_cast<Derived>(get(id)); | |
69 } | |
70 | |
71 private: | |
72 mutable QMutex m_mutex; | |
73 std::map<Id, std::shared_ptr<Item>> m_items; | |
74 }; | |
75 /* | |
76 class Imagined : public WithId { | |
77 }; | |
78 | |
79 class ImaginedById | |
80 { | |
81 public: | |
82 static void add(std::shared_ptr<Imagined> imagined) { | |
83 m_byId.add(imagined); | |
84 } | |
85 | |
86 static void release(Id id) { | |
87 m_byId.release(id); | |
88 } | |
89 | |
90 static std::shared_ptr<Imagined> get(Id id) { | |
91 return m_byId.get(id); | |
92 } | |
93 | |
94 template <typename Derived> | |
95 static | |
96 std::shared_ptr<Derived> getAs(Id id) { | |
97 return m_byId.getAs<Derived>(id); | |
98 } | |
99 | |
100 private: | |
101 static ById<Imagined> m_byId; | |
102 }; | |
103 */ | |
104 #endif | |
105 |