From bdabca9432d898b65ad74bba7d87684234e7371f Mon Sep 17 00:00:00 2001 From: David Blaikie Date: Wed, 19 Aug 2015 23:07:27 +0000 Subject: [PATCH] Allow Optionals to be compared to None This is something like nullopt in std::experimental::optional. Optional could already be constructed from None, so this seems like an obvious extension from there. I have a use in a future patch for Clang, though it may not go that way/end up used - so this seemed worth committing now regardless. llvm-svn: 245518 --- include/llvm/ADT/Optional.h | 19 +++++++++++++++++++ unittests/ADT/OptionalTest.cpp | 13 +++++++++++++ 2 files changed, 32 insertions(+) diff --git a/include/llvm/ADT/Optional.h b/include/llvm/ADT/Optional.h index 855ab890392..d9acaf6d23b 100644 --- a/include/llvm/ADT/Optional.h +++ b/include/llvm/ADT/Optional.h @@ -159,6 +159,25 @@ template struct isPodLike > { template void operator==(const Optional &X, const Optional &Y); +template +bool operator==(const Optional &X, NoneType) { + return !X.hasValue(); +} + +template +bool operator==(NoneType, const Optional &X) { + return X == None; +} + +template +bool operator!=(const Optional &X, NoneType) { + return !(X == None); +} + +template +bool operator!=(NoneType, const Optional &X) { + return X != None; +} /// \brief Poison comparison between two \c Optional objects. Clients needs to /// explicitly compare the underlying values and account for empty \c Optional /// objects. diff --git a/unittests/ADT/OptionalTest.cpp b/unittests/ADT/OptionalTest.cpp index 92c4eec487a..18b59e31581 100644 --- a/unittests/ADT/OptionalTest.cpp +++ b/unittests/ADT/OptionalTest.cpp @@ -377,5 +377,18 @@ TEST_F(OptionalTest, MoveGetValueOr) { #endif // LLVM_HAS_RVALUE_REFERENCE_THIS +TEST_F(OptionalTest, NoneComparison) { + Optional o; + EXPECT_EQ(o, None); + EXPECT_EQ(None, o); + EXPECT_FALSE(o != None); + EXPECT_FALSE(None != o); + o = 3; + EXPECT_FALSE(o == None); + EXPECT_FALSE(None == o); + EXPECT_TRUE(o != None); + EXPECT_TRUE(None != o); +} + } // end anonymous namespace