Bitcoin ABC  0.24.7
P2P Digital Currency
ref.h
Go to the documentation of this file.
1 // Copyright (c) 2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #ifndef BITCOIN_UTIL_REF_H
6 #define BITCOIN_UTIL_REF_H
7 
8 #include <util/check.h>
9 
10 #include <typeindex>
11 
12 namespace util {
13 
21 class Ref {
22 public:
23  Ref() = default;
24  template <typename T> Ref(T &value) { Set(value); }
25  template <typename T> T &Get() const {
26  CHECK_NONFATAL(Has<T>());
27  return *static_cast<T *>(m_value);
28  }
29  template <typename T> void Set(T &value) {
30  m_value = &value;
31  m_type = std::type_index(typeid(T));
32  }
33  template <typename T> bool Has() const {
34  return m_value && m_type == std::type_index(typeid(T));
35  }
36  void Clear() {
37  m_value = nullptr;
38  m_type = std::type_index(typeid(void));
39  }
40 
41 private:
42  void *m_value = nullptr;
43  std::type_index m_type = std::type_index(typeid(void));
44 };
45 
46 } // namespace util
47 
48 #endif // BITCOIN_UTIL_REF_H
util::Ref::Ref
Ref(T &value)
Definition: ref.h:24
check.h
CHECK_NONFATAL
#define CHECK_NONFATAL(condition)
Throw a NonFatalCheckError when the condition evaluates to false.
Definition: check.h:34
util::Ref::Get
T & Get() const
Definition: ref.h:25
util::Ref::Set
void Set(T &value)
Definition: ref.h:29
util::Ref::m_value
void * m_value
Definition: ref.h:42
util::Ref
Type-safe dynamic reference.
Definition: ref.h:21
util::Ref::m_type
std::type_index m_type
Definition: ref.h:43
util::Ref::Ref
Ref()=default
util::Ref::Has
bool Has() const
Definition: ref.h:33
util::Ref::Clear
void Clear()
Definition: ref.h:36
util
Definition: httprpc.h:13