Line data Source code
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 : 14 : /** 15 : * Type-safe dynamic reference. 16 : * 17 : * This implements a small subset of the functionality in C++17's std::any 18 : * class, and can be dropped when the project updates to C++17 19 : * (https://github.com/bitcoin/bitcoin/issues/16684) 20 : */ 21 : class Ref 22 : { 23 : public: 24 10 : Ref() = default; 25 38272 : template<typename T> Ref(T& value) { Set(value); } 26 39997 : template<typename T> T& Get() const { CHECK_NONFATAL(Has<T>()); return *static_cast<T*>(m_value); } 27 19138 : template<typename T> void Set(T& value) { m_value = &value; m_type = std::type_index(typeid(T)); } 28 79991 : template<typename T> bool Has() const { return m_value && m_type == std::type_index(typeid(T)); } 29 1 : void Clear() { m_value = nullptr; m_type = std::type_index(typeid(void)); } 30 : 31 : private: 32 19141 : void* m_value = nullptr; 33 19141 : std::type_index m_type = std::type_index(typeid(void)); 34 : }; 35 : 36 : } // namespace util 37 : 38 : #endif // BITCOIN_UTIL_REF_H