-
Notifications
You must be signed in to change notification settings - Fork 1
/
manager.h
94 lines (73 loc) · 1.25 KB
/
manager.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifndef MANAGER_H
#define MANAGER_H
#include <string>
#include <map>
// base class for manager objects
class ManagedItem {
int refcount;
public:
std::string name;
ManagedItem(std::string n): name(n), refcount(0) {}
virtual ~ManagedItem() {}
void addref()
{
++refcount;
}
bool delref()
{
return --refcount==0;
}
};
template <class IDTYPE>
class Manager {
public:
std::map<std::string, IDTYPE> names;
std::map<IDTYPE, ManagedItem*> items;
Manager()
{
}
virtual IDTYPE add(std::string name) = 0;
virtual void del(IDTYPE id)
{
if (items[id]->delref()) {
ManagedItem *i = items[id];
doDelete(id);
names.erase(names.find(i->name));
items.erase(items.find(id));
delete i;
}
}
void delbyname(std::string name)
{
if (has(name)) del(get(name));
}
virtual void doDelete(IDTYPE id) {}
bool has(std::string name)
{
return (names.find(name) != names.end());
}
IDTYPE get(std::string name)
{
return names[name];
}
protected:
void do_add(std::string name, IDTYPE id, ManagedItem* item)
{
names[name] = id;
item->addref();
items[id] = item;
}
};
class SimpleManager : public Manager<int> {
int baseid;
public:
SimpleManager() : baseid(0)
{
}
protected:
int nextID()
{
return baseid++;
}
};
#endif