diff --git a/llvm/include/llvm/ADT/Optional.h b/llvm/include/llvm/ADT/Optional.h index 1862a2d703aad..874183ce190e5 100644 --- a/llvm/include/llvm/ADT/Optional.h +++ b/llvm/include/llvm/ADT/Optional.h @@ -342,6 +342,12 @@ template class Optional { /// Apply a function to the value if present; otherwise return None. template + auto transform(const Function &F) const & -> Optional { + if (*this) + return F(value()); + return None; + } + template auto map(const Function &F) const & -> Optional { if (*this) return F(value()); @@ -365,6 +371,13 @@ template class Optional { /// Apply a function to the value if present; otherwise return None. template + auto transform( + const Function &F) && -> Optional { + if (*this) + return F(std::move(*this).value()); + return None; + } + template auto map(const Function &F) && -> Optional { if (*this) diff --git a/llvm/unittests/ADT/OptionalTest.cpp b/llvm/unittests/ADT/OptionalTest.cpp index 3db84ed4c3306..c583ff0df9af1 100644 --- a/llvm/unittests/ADT/OptionalTest.cpp +++ b/llvm/unittests/ADT/OptionalTest.cpp @@ -603,6 +603,40 @@ TEST(OptionalTest, MoveValueOr) { EXPECT_EQ(2u, MoveOnly::Destructions); } +TEST(OptionalTest, Transform) { + Optional A; + + Optional B = A.transform([&](int N) { return N + 1; }); + EXPECT_FALSE(B.has_value()); + + A = 3; + Optional C = A.transform([&](int N) { return N + 1; }); + EXPECT_TRUE(C.has_value()); + EXPECT_EQ(4, C.value()); +} + +TEST(OptionalTest, MoveTransform) { + Optional A; + + MoveOnly::ResetCounts(); + Optional B = + std::move(A).transform([&](const MoveOnly &M) { return M.val + 2; }); + EXPECT_FALSE(B.has_value()); + EXPECT_EQ(0u, MoveOnly::MoveConstructions); + EXPECT_EQ(0u, MoveOnly::MoveAssignments); + EXPECT_EQ(0u, MoveOnly::Destructions); + + A = MoveOnly(5); + MoveOnly::ResetCounts(); + Optional C = + std::move(A).transform([&](const MoveOnly &M) { return M.val + 2; }); + EXPECT_TRUE(C.has_value()); + EXPECT_EQ(7, C.value()); + EXPECT_EQ(0u, MoveOnly::MoveConstructions); + EXPECT_EQ(0u, MoveOnly::MoveAssignments); + EXPECT_EQ(0u, MoveOnly::Destructions); +} + struct EqualTo { template static bool apply(const T &X, const U &Y) { return X == Y;