supertux
typed_uid.hpp
1 // SuperTux
2 // Copyright (C) 2021 A. Semphris <semphris@protonmail.com>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16 
17 #ifndef HEADER_SUPERTUX_UTIL_TYPED_UID_HPP
18 #define HEADER_SUPERTUX_UTIL_TYPED_UID_HPP
19 
20 #include "util/uid.hpp"
21 
22 #include "supertux/sector.hpp"
23 
29 template<class T>
30 class TypedUID : public UID
31 {
32 public:
33  TypedUID() : UID() {}
34  TypedUID(const T* object) : UID() { if (object) *this = object->get_uid(); }
35  TypedUID(const TypedUID& other) = default;
36  TypedUID& operator=(const TypedUID& other) = default;
37 
38  inline T* get() const
39  {
40  if (m_value == 0 || !Sector::current())
41  return nullptr;
42 
43  auto* object = Sector::get().get_object_by_uid<T>(*this);
44 
45  // Would break const correctness
46 #if 0
47  if (!object)
48  {
49  *this = UID();
50  }
51 #endif
52 
53  return object;
54  }
55 
56  inline TypedUID& operator=(const T* object)
57  {
58  *this = object ? object->get_uid() : UID();
59  return *this;
60  }
61 
62  inline TypedUID& operator=(const UID& other)
63  {
64  UID::operator=(other);
65  return *this;
66  }
67 
68  inline T* operator->() const
69  {
70  return get();
71  }
72 
73  inline T& operator*() const
74  {
75  T* t = get();
76  if (!t)
77  throw std::runtime_error("Attempt to dereference invalid TypedUID");
78 
79  return *t;
80  }
81 
82  inline bool operator==(const T* object) const
83  {
84  return (!object && m_value == 0) || object->get_uid() == *this;
85  }
86 
87  inline bool operator!=(const T* object) const
88  {
89  return object ? object->get_uid() != *this : m_value == 0;
90  }
91 
92  inline operator bool() const {
93  return m_value != 0 && Sector::current() && Sector::get().get_object_by_uid<T>(*this);
94  }
95 };
96 
97 template<class T>
98 inline bool operator==(const T* object, const TypedUID<T>& typed_uid) {
99  return typed_uid == object;
100 }
101 
102 template<class T>
103 inline bool operator!=(const T* object, const TypedUID<T>& typed_uid) {
104  return typed_uid != object;
105 }
106 
107 #endif
108 
109 /* EOF */
Typed UIDs allows storing GameObjects as UID while offering to option to use the object either as if ...
Definition: typed_uid.hpp:30
Definition: uid.hpp:37
static Sector & get()
get currently activated sector.
Definition: sector.hpp:74