1+ /* *
2+ * @project: Overload
3+ * @author: Overload Tech.
4+ * @restrictions: This software may not be resold, redistributed or otherwise conveyed to a third party.
5+ */
6+
7+ #pragma once
8+
9+ #include < variant>
10+
11+ namespace OvTools ::Utils
12+ {
13+ /* *
14+ * A simple class that can represent a reference or a value of the given type.
15+ * The usage of the data is the same for both usages.
16+ * The goal is to be able to instanciate objects that can be a reference or a value without
17+ * taking care of what it is.
18+ */
19+ template <typename T>
20+ class ReferenceOrValue
21+ {
22+ public:
23+ /* *
24+ * Construct the ReferenceOrValue instance with a reference
25+ * @param p_reference
26+ */
27+ ReferenceOrValue (std::reference_wrapper<T> p_reference) : m_data{ &p_reference.get () }
28+ {
29+ }
30+
31+ /* *
32+ * Construct the ReferenceOrValue instance with a value
33+ * @param p_value
34+ */
35+ ReferenceOrValue (T p_value = T()) : m_data{ p_value }
36+ {
37+ }
38+
39+ /* *
40+ * Make the ReferenceOrValue a reference
41+ * @param p_reference
42+ */
43+ void MakeReference (T& p_reference)
44+ {
45+ m_data = &p_reference;
46+ }
47+
48+ /* *
49+ * Make the ReferenceOrValue a value
50+ * @param p_value
51+ */
52+ void MakeValue (T p_value = T())
53+ {
54+ m_data = p_value;
55+ }
56+
57+ /* *
58+ * Implicit conversion of a ReferenceOrValue to a T
59+ */
60+ operator T ()
61+ {
62+ return Get ();
63+ }
64+
65+ /* *
66+ * Assignment operator thats call the setter of the ReferenceOrValue instance
67+ * @param p_value
68+ */
69+ ReferenceOrValue<T>& operator =(T p_value)
70+ {
71+ Set (p_value);
72+ return *this ;
73+ }
74+
75+ /* *
76+ * Returns the value (From reference or directly from the value)
77+ */
78+ T Get () const
79+ {
80+ if (auto pval = std::get_if<T>(&m_data))
81+ return *pval;
82+ else
83+ return *std::get<T*>(m_data);
84+ }
85+
86+ /* *
87+ * Sets the value (To the reference or directly to the value)
88+ * @param p_value
89+ */
90+ void Set (T p_value)
91+ {
92+ if (auto pval = std::get_if<T>(&m_data))
93+ * pval = p_value;
94+ else
95+ *std::get<T*>(m_data) = p_value;
96+ }
97+
98+ private:
99+ std::variant<T, T*> m_data;
100+ };
101+ }
0 commit comments