|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <type_traits> |
| 4 | + |
| 5 | +namespace sentry { |
| 6 | + |
| 7 | +// Casts between related classes without the cost of dynamic_cast. |
| 8 | +// Declare with SENTRY_CASTABLE in every participating class, naming Castable |
| 9 | +// as the base in the root class. |
| 10 | +class Castable { |
| 11 | +public: |
| 12 | + struct TypeInfo { |
| 13 | + const TypeInfo *parent; |
| 14 | + }; |
| 15 | + |
| 16 | + static constexpr TypeInfo type_info{ nullptr }; |
| 17 | + |
| 18 | + // Returns true if p_from is a T, or derives from T. Null is safe and never matches. |
| 19 | + template <typename T> |
| 20 | + static bool is_class(const Castable *p_from) { |
| 21 | + static_assert(std::is_same_v<typename T::castable_self, T>, |
| 22 | + "T must declare SENTRY_CASTABLE"); |
| 23 | + if (!p_from) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + const TypeInfo *t = p_from->get_type_info(); |
| 27 | + while (t) { |
| 28 | + if (t == &T::type_info) { |
| 29 | + return true; |
| 30 | + } |
| 31 | + t = t->parent; |
| 32 | + } |
| 33 | + return false; |
| 34 | + } |
| 35 | + |
| 36 | + // Returns p_from as T, or null if it isn't one. Null is safe. |
| 37 | + template <typename T> |
| 38 | + static T *cast_to(Castable *p_from) { |
| 39 | + return is_class<T>(p_from) ? static_cast<T *>(p_from) : nullptr; |
| 40 | + } |
| 41 | + |
| 42 | + // Returns p_from as T, or null if it isn't one. Null is safe. |
| 43 | + template <typename T> |
| 44 | + static const T *cast_to(const Castable *p_from) { |
| 45 | + return is_class<T>(p_from) ? static_cast<const T *>(p_from) : nullptr; |
| 46 | + } |
| 47 | + |
| 48 | + virtual ~Castable() = default; |
| 49 | + |
| 50 | +protected: |
| 51 | + virtual const TypeInfo *get_type_info() const = 0; |
| 52 | +}; |
| 53 | + |
| 54 | +} //namespace sentry |
| 55 | + |
| 56 | +// Adds type info to a castable class. Add at the top of the class body. |
| 57 | +#define SENTRY_CASTABLE(m_class, m_base) \ |
| 58 | +public: \ |
| 59 | + using castable_self = m_class; \ |
| 60 | + static constexpr ::sentry::Castable::TypeInfo type_info{ &m_base::type_info }; \ |
| 61 | + \ |
| 62 | +protected: \ |
| 63 | + virtual const ::sentry::Castable::TypeInfo *get_type_info() const override { \ |
| 64 | + static_assert(std::is_base_of_v<m_base, m_class>, \ |
| 65 | + #m_base " must be a base of " #m_class "."); \ |
| 66 | + return &type_info; \ |
| 67 | + } \ |
| 68 | + \ |
| 69 | +private: |
0 commit comments