Skip to content

Commit 0775077

Browse files
nicotimschumi
authored andcommitted
AK: Allow creating a MaybeOwned<Superclass> from a MaybeOwned<Subclass>
1 parent a72770c commit 0775077

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

AK/MaybeOwned.h

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ class MaybeOwned {
3232
MaybeOwned(MaybeOwned&&) = default;
3333
MaybeOwned& operator=(MaybeOwned&&) = default;
3434

35+
template<DerivedFrom<T> U>
36+
MaybeOwned(MaybeOwned<U>&& other)
37+
: m_handle(downcast<U, T>(move(other.m_handle)))
38+
{
39+
}
40+
3541
T* ptr()
3642
{
3743
if (m_handle.template has<T*>())
@@ -57,7 +63,22 @@ class MaybeOwned {
5763
bool is_owned() const { return m_handle.template has<NonnullOwnPtr<T>>(); }
5864

5965
private:
60-
Variant<NonnullOwnPtr<T>, T*> m_handle;
66+
template<typename F>
67+
friend class MaybeOwned;
68+
69+
template<typename HT>
70+
using Handle = Variant<NonnullOwnPtr<HT>, HT*>;
71+
72+
template<typename U, typename D>
73+
Handle<D> downcast(Handle<U>&& variant)
74+
{
75+
if (variant.template has<U*>())
76+
return variant.template get<U*>();
77+
else
78+
return static_cast<NonnullOwnPtr<T>&&>(move(variant.template get<NonnullOwnPtr<U>>()));
79+
}
80+
81+
Handle<T> m_handle;
6182
};
6283

6384
}

0 commit comments

Comments
 (0)