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