From: David Blaikie Date: Wed, 19 Aug 2015 23:07:27 +0000 (+0000) Subject: Allow Optionals to be compared to None X-Git-Url: http://plrg.eecs.uci.edu/git/?p=oota-llvm.git;a=commitdiff_plain;h=116832190dc04f511dacff847742733cc957d46a;ds=inline 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. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@245518 91177308-0d34-0410-b5e6-96231b3b80d8 --- 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