Add implicit conversions for box from derived to base type
This commit is contained in:
10
asl/box.hpp
10
asl/box.hpp
@ -35,6 +35,13 @@ public:
|
||||
, m_alloc{ASL_MOVE(other.m_alloc)}
|
||||
{}
|
||||
|
||||
template<is_object U>
|
||||
requires convertible_from<T*, U*>
|
||||
constexpr box(box<U, Allocator>&& other) // NOLINT(*-explicit-conversions)
|
||||
: m_ptr{exchange(other.m_ptr, nullptr)}
|
||||
, m_alloc{ASL_MOVE(other.m_alloc)}
|
||||
{}
|
||||
|
||||
constexpr box& operator=(box&& other)
|
||||
{
|
||||
if (this == &other) { return *this; }
|
||||
@ -93,6 +100,9 @@ public:
|
||||
|
||||
template<is_object U, allocator A>
|
||||
friend constexpr U* leak(box<U, A>&&);
|
||||
|
||||
template<is_object U, allocator A>
|
||||
friend class box;
|
||||
};
|
||||
|
||||
template<is_object T, allocator Allocator = DefaultAllocator, typename... Args>
|
||||
|
@ -76,3 +76,27 @@ ASL_TEST(niche)
|
||||
ASL_TEST_EXPECT(!opt2.has_value());
|
||||
ASL_TEST_EXPECT(destroyed);
|
||||
}
|
||||
|
||||
class Base
|
||||
{
|
||||
public:
|
||||
virtual ~Base() = default;
|
||||
virtual int number() { return 1; }
|
||||
};
|
||||
|
||||
class Derived : public Base
|
||||
{
|
||||
public:
|
||||
int number() override { return 2; }
|
||||
};
|
||||
|
||||
static_assert(asl::convertible_from<asl::box<Base>, asl::box<Derived>>);
|
||||
static_assert(asl::convertible_from<asl::box<Base>, asl::box<Base>>);
|
||||
static_assert(!asl::convertible_from<asl::box<Derived>, asl::box<Base>>);
|
||||
static_assert(!asl::convertible_from<asl::box<int>, asl::box<float>>);
|
||||
|
||||
ASL_TEST(derived)
|
||||
{
|
||||
asl::box<Base> obj = asl::make_box<Derived>();
|
||||
ASL_TEST_ASSERT(obj->number() == 2);
|
||||
}
|
||||
|
Reference in New Issue
Block a user