qxLib
class_id.h
Go to the documentation of this file.
1 /**
2 
3  @file class_id.h
4  @author Khrapov
5  @date 11.09.2021
6  @copyright © Nick Khrapov, 2021. All right reserved.
7 
8 **/
9 #pragma once
10 
13 #include <qx/meta/type_strings.h>
14 
15 namespace qx
16 {
17 
18 /**
19 
20  @class class_id
21  @brief Class id, unique for each class using qx rtti system
22  @author Khrapov
23  @date 5.07.2024
24 
25 **/
26 class class_id
27 {
28  friend std::hash<class_id>;
29 
30 public:
31  constexpr class_id() noexcept = default;
32  QX_COPYMOVABLE(class_id);
33 
34  /**
35  @brief Create a class id for a given type (the type doesn't require to use qx rtti system)
36  @tparam T - a type
37  @retval - T id
38  **/
39  template<class T>
40  constexpr static class_id create();
41 
42  constexpr bool operator==(const class_id& other) const noexcept;
43  constexpr bool operator!=(const class_id& other) const noexcept;
44  constexpr bool operator<(const class_id& other) const noexcept;
45 
46  /**
47  @brief Get class name
48  @retval - class name
49  **/
50  constexpr string_view get_class_name() const;
51 
52 private:
53  string_view m_svClassName = QX_TEXT("Empty name");
54  size_t m_nId = 0;
55 };
56 
57 constexpr bool class_id::operator==(const class_id& other) const noexcept
58 {
59  return m_nId == other.m_nId;
60 }
61 
62 constexpr bool class_id::operator!=(const class_id& other) const noexcept
63 {
64  return m_nId != other.m_nId;
65 }
66 
67 constexpr bool class_id::operator<(const class_id& other) const noexcept
68 {
69  return m_nId < other.m_nId;
70 }
71 
72 constexpr string_view class_id::get_class_name() const
73 {
74  return m_svClassName;
75 }
76 
77 template<class T>
78 constexpr class_id class_id::create()
79 {
80  class_id result;
81  result.m_svClassName = type_strings<T, char_type>::get_signature();
82  result.m_nId = string_hash(result.m_svClassName);
83  return result;
84 }
85 
86 } // namespace qx
87 
88 template<>
89 struct std::hash<qx::class_id>
90 {
91  constexpr size_t operator()(const qx::class_id& id) const noexcept
92  {
93  return id.m_nId;
94  }
95 };
96 
97 template<>
98 struct std::formatter<qx::class_id, qx::char_type> : qx::basic_formatter
99 {
100  template<class FormatContextType>
101  constexpr auto format(const qx::class_id& id, FormatContextType& ctx) const
102  {
103  return std::format_to(ctx.out(), QX_TEXT("{}"), id.get_class_name());
104  }
105 };
String hash object.
Definition: string_hash.h:38
Class id, unique for each class using qx rtti system.
Definition: class_id.h:27
constexpr static class_id create()
Create a class id for a given type (the type doesn't require to use qx rtti system)
constexpr string_view get_class_name() const
Get class name.
Definition: class_id.h:72
static constexpr string_view_type get_signature()
Get type signature (full name with template parameters)