From 691c817b340d10e806dc3b1834d2a8fcc5e681fd Mon Sep 17 00:00:00 2001 From: Russell Yanofsky Date: Fri, 17 Apr 2020 11:15:55 -0400 Subject: Add util::Ref class as temporary alternative for c++17 std::any This commit does not change behavior --- src/util/ref.h | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/util/ref.h (limited to 'src/util/ref.h') diff --git a/src/util/ref.h b/src/util/ref.h new file mode 100644 index 0000000000..9685ea9fec --- /dev/null +++ b/src/util/ref.h @@ -0,0 +1,38 @@ +// Copyright (c) 2020 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_UTIL_REF_H +#define BITCOIN_UTIL_REF_H + +#include + +#include + +namespace util { + +/** + * Type-safe dynamic reference. + * + * This implements a small subset of the functionality in C++17's std::any + * class, and can be dropped when the project updates to C++17 + * (https://github.com/bitcoin/bitcoin/issues/16684) + */ +class Ref +{ +public: + Ref() = default; + template Ref(T& value) { Set(value); } + template T& Get() const { CHECK_NONFATAL(Has()); return *static_cast(m_value); } + template void Set(T& value) { m_value = &value; m_type = std::type_index(typeid(T)); } + template bool Has() const { return m_value && m_type == std::type_index(typeid(T)); } + void Clear() { m_value = nullptr; m_type = std::type_index(typeid(void)); } + +private: + void* m_value = nullptr; + std::type_index m_type = std::type_index(typeid(void)); +}; + +} // namespace util + +#endif // BITCOIN_UTIL_REF_H -- cgit v1.2.3