Add emplace to option

This commit is contained in:
2024-11-02 18:32:17 +01:00
parent afd8e711ab
commit be34f768e0
2 changed files with 35 additions and 0 deletions

View File

@ -387,6 +387,15 @@ public:
{ {
return has_value() ? ASL_MOVE(value()) : static_cast<T>(ASL_FWD(other_value)); return has_value() ? ASL_MOVE(value()) : static_cast<T>(ASL_FWD(other_value));
} }
template<typename... Args>
T& emplace(Args&&... args) &
requires constructible<T, Args&&...>
{
if (m_has_value) { reset(); }
construct(ASL_FWD(args)...);
return value();
}
}; };
template<typename T> template<typename T>

View File

@ -198,3 +198,29 @@ ASL_TEST(value_or)
ASL_TEST_EXPECT(a.value_or(5) == 5); ASL_TEST_EXPECT(a.value_or(5) == 5);
ASL_TEST_EXPECT(b.value_or(5) == 2); ASL_TEST_EXPECT(b.value_or(5) == 2);
} }
ASL_TEST(emplace)
{
asl::option<int> a = asl::nullopt;
a.emplace(42);
ASL_TEST_EXPECT(a.has_value());
ASL_TEST_EXPECT(a.value() == 42);
}
ASL_TEST(emplace_destroys_previous)
{
bool b1 = false;
bool b2 = false;
{
asl::option<DestructorObserver> a{&b1};
ASL_TEST_EXPECT(!b1);
a.emplace(&b2);
ASL_TEST_EXPECT(b1);
ASL_TEST_EXPECT(!b2);
}
ASL_TEST_EXPECT(b2);
}