]> git.tdb.fi Git - libs/game.git/blob - source/game/handle.h
Make it possible to retrieve components and systems of a particular type
[libs/game.git] / source / game / handle.h
1 #ifndef MSP_GAME_HANDLE_H_
2 #define MSP_GAME_HANDLE_H_
3
4 #include <stdexcept>
5 #include "pool.h"
6
7 namespace Msp::Game {
8
9 class invalid_handle: public std::logic_error
10 {
11 public:
12         invalid_handle(const std::type_info &);
13 };
14
15 template<typename T>
16 class Handle
17 {
18         template<typename U>
19         friend class Handle;
20
21 protected:
22         T *ptr = nullptr;
23
24 public:
25         Handle() = default;
26         Handle(nullptr_t) { }
27
28         template<typename U>
29                 requires std::is_base_of_v<T, U>
30         Handle(const Handle<U> &other): ptr(other.ptr) { }
31
32         static Handle from_object(T *o) { Handle h; h.ptr = o; return h; }
33
34         T *get() const { return ptr; }
35         T &operator*() const { return *ptr; }
36         T *operator->() const { return ptr; }
37         explicit operator bool() const { return ptr; }
38
39         bool operator==(const Handle &other) const = default;
40 };
41
42 template<typename T, typename U>
43         requires std::is_base_of_v<U, T>
44 Handle<T> dynamic_handle_cast(Handle<U> h)
45 {
46         return Handle<T>::from_object(dynamic_cast<T *>(h.get()));
47 }
48
49 } // namespace Msp::Game
50
51 #endif