From 224048d0f4022f91c2074daddf9dcafbf11f2be9 Mon Sep 17 00:00:00 2001 From: Steven Le Rouzic Date: Thu, 30 Jan 2025 23:34:12 +0100 Subject: Add implicit conversions for box from derived to base type --- asl/box.hpp | 10 ++++++++++ asl/tests/box_tests.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) (limited to 'asl') diff --git a/asl/box.hpp b/asl/box.hpp index 795b6dd..9d3c7f0 100644 --- a/asl/box.hpp +++ b/asl/box.hpp @@ -35,6 +35,13 @@ public: , m_alloc{ASL_MOVE(other.m_alloc)} {} + template + requires convertible_from + constexpr box(box&& 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 friend constexpr U* leak(box&&); + + template + friend class box; }; template diff --git a/asl/tests/box_tests.cpp b/asl/tests/box_tests.cpp index edb574c..3faf121 100644 --- a/asl/tests/box_tests.cpp +++ b/asl/tests/box_tests.cpp @@ -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>); +static_assert(asl::convertible_from, asl::box>); +static_assert(!asl::convertible_from, asl::box>); +static_assert(!asl::convertible_from, asl::box>); + +ASL_TEST(derived) +{ + asl::box obj = asl::make_box(); + ASL_TEST_ASSERT(obj->number() == 2); +} -- cgit