Horizon
uuid_ptr.hpp
1 #pragma once
2 #include "uuid.hpp"
3 #include <assert.h>
4 #include <map>
5 #include <type_traits>
6 
7 namespace horizon {
8 template <typename T> class uuid_ptr {
9 private:
10  typedef typename std::remove_const<T>::type T_without_const;
11 
12 public:
13  uuid_ptr() : ptr(nullptr)
14  {
15  }
16  uuid_ptr(const UUID &uu) : ptr(nullptr), uuid(uu)
17  {
18  }
19  uuid_ptr(T *p, const UUID &uu) : ptr(p), uuid(uu)
20  {
21  }
22  uuid_ptr(T *p) : ptr(p), uuid(p ? p->get_uuid() : UUID())
23  {
24  /* static_assert(
25  std::is_base_of<T, decltype(*p)>::value,
26  "T must be a descendant of MyBase"
27  );*/
28  }
29  T &operator*()
30  {
31 #ifdef UUID_PTR_CHECK
32  if (ptr) {
33  assert(ptr->get_uuid() == uuid);
34  }
35 #endif
36  return *ptr;
37  }
38 
39  T *operator->() const
40  {
41 #ifdef UUID_PTR_CHECK
42  if (ptr) {
43  assert(ptr->get_uuid() == uuid);
44  }
45 #endif
46  return ptr;
47  }
48 
49  operator T *() const
50  {
51 #ifdef UUID_PTR_CHECK
52  if (ptr) {
53  assert(ptr->get_uuid() == uuid);
54  }
55 #endif
56  return ptr;
57  }
58 
59  T *ptr;
60  UUID uuid;
61  void update(std::map<UUID, T> &map)
62  {
63  if (uuid) {
64  if (map.count(uuid)) {
65  ptr = &map.at(uuid);
66  }
67  else {
68  ptr = nullptr;
69  }
70  }
71  }
72  void update(const std::map<UUID, T_without_const> &map)
73  {
74  if (uuid) {
75  if (map.count(uuid)) {
76  ptr = &map.at(uuid);
77  }
78  else {
79  ptr = nullptr;
80  }
81  }
82  }
83 };
84 } // namespace horizon