From be34f768e093cb6752ab81fde3ab529861a8a6a8 Mon Sep 17 00:00:00 2001 From: Steven Le Rouzic Date: Sat, 2 Nov 2024 18:32:17 +0100 Subject: Add emplace to option --- asl/option.hpp | 9 +++++++++ asl/tests/option_tests.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) (limited to 'asl') diff --git a/asl/option.hpp b/asl/option.hpp index bb266ab..ab88992 100644 --- a/asl/option.hpp +++ b/asl/option.hpp @@ -387,6 +387,15 @@ public: { return has_value() ? ASL_MOVE(value()) : static_cast(ASL_FWD(other_value)); } + + template + T& emplace(Args&&... args) & + requires constructible + { + if (m_has_value) { reset(); } + construct(ASL_FWD(args)...); + return value(); + } }; template diff --git a/asl/tests/option_tests.cpp b/asl/tests/option_tests.cpp index ec6e957..73998f8 100644 --- a/asl/tests/option_tests.cpp +++ b/asl/tests/option_tests.cpp @@ -198,3 +198,29 @@ ASL_TEST(value_or) ASL_TEST_EXPECT(a.value_or(5) == 5); ASL_TEST_EXPECT(b.value_or(5) == 2); } + +ASL_TEST(emplace) +{ + asl::option 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 a{&b1}; + ASL_TEST_EXPECT(!b1); + + a.emplace(&b2); + ASL_TEST_EXPECT(b1); + ASL_TEST_EXPECT(!b2); + } + + ASL_TEST_EXPECT(b2); +} -- cgit