From 1e0466c4ab26e82abed7f8f263dfe6a2a543cc1a Mon Sep 17 00:00:00 2001 From: Rob Hughes Date: Wed, 11 Sep 2019 09:51:13 +0100 Subject: Add "explicit" qualifier to Optional -> bool conversion method This prevents unintended conversions that could lead to incorrect code compiling, e.g. Optional == Optional Also add comparison (==) operator to compare two Optionals. Update unit tests accordingly Change-Id: I6f975de7e666ba1ffe16c3ab50643116c6317135 Signed-off-by: Rob Hughes --- include/armnn/Optional.hpp | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'include') diff --git a/include/armnn/Optional.hpp b/include/armnn/Optional.hpp index 29be3829a7..863b122716 100644 --- a/include/armnn/Optional.hpp +++ b/include/armnn/Optional.hpp @@ -55,7 +55,10 @@ public: return m_HasValue; } - operator bool() const noexcept + /// Conversion to bool, so can be used in if-statements and similar contexts expecting a bool. + /// Note this is explicit so that it doesn't get implicitly converted to a bool in unwanted cases, + /// for example "Optional == Optional" should not compile. + explicit operator bool() const noexcept { return has_value(); } @@ -278,6 +281,21 @@ public: template explicit Optional(ConstructInPlace, Args&&... args) : BaseSwitch(CONSTRUCT_IN_PLACE, std::forward(args)...) {} + + /// Two optionals are considered equal if they are both empty or both contain values which + /// themselves are considered equal (via their own == operator). + bool operator==(const Optional& rhs) const + { + if (!this->has_value() && !rhs.has_value()) + { + return true; + } + if (this->has_value() && rhs.has_value() && this->value() == rhs.value()) + { + return true; + } + return false; + } }; // Utility template that constructs an object of type T in-place and wraps -- cgit v1.2.1