AK: Allow creating a MaybeOwned<Superclass> from a MaybeOwned<Subclass>

This commit is contained in:
Nico Weber 2024-03-22 13:09:52 -04:00 committed by Tim Schumacher
parent a72770cdf6
commit 07750774cf
Notes: sideshowbarker 2024-07-17 06:54:15 +09:00

View file

@ -32,6 +32,12 @@ public:
MaybeOwned(MaybeOwned&&) = default; MaybeOwned(MaybeOwned&&) = default;
MaybeOwned& operator=(MaybeOwned&&) = default; MaybeOwned& operator=(MaybeOwned&&) = default;
template<DerivedFrom<T> U>
MaybeOwned(MaybeOwned<U>&& other)
: m_handle(downcast<U, T>(move(other.m_handle)))
{
}
T* ptr() T* ptr()
{ {
if (m_handle.template has<T*>()) if (m_handle.template has<T*>())
@ -57,7 +63,22 @@ public:
bool is_owned() const { return m_handle.template has<NonnullOwnPtr<T>>(); } bool is_owned() const { return m_handle.template has<NonnullOwnPtr<T>>(); }
private: private:
Variant<NonnullOwnPtr<T>, T*> m_handle; template<typename F>
friend class MaybeOwned;
template<typename HT>
using Handle = Variant<NonnullOwnPtr<HT>, HT*>;
template<typename U, typename D>
Handle<D> downcast(Handle<U>&& variant)
{
if (variant.template has<U*>())
return variant.template get<U*>();
else
return static_cast<NonnullOwnPtr<T>&&>(move(variant.template get<NonnullOwnPtr<U>>()));
}
Handle<T> m_handle;
}; };
} }