From: Sebastian Messmer Date: Wed, 8 Feb 2017 19:41:13 +0000 (-0800) Subject: Specialise std::hash for folly::Optional X-Git-Tag: v2017.03.06.00~48 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=c141f6ec365fcf87af33f7de9ad66d62520729c1;p=folly.git Specialise std::hash for folly::Optional Summary: This allows using folly::Optional in std::unordered_map and std::unordered_set. Reviewed By: luciang Differential Revision: D4469938 fbshipit-source-id: b86b1a4510379b337e9de83471a4aafce6d5a6cb --- diff --git a/folly/Optional.h b/folly/Optional.h index 61e71c1f..5350b2ee 100644 --- a/folly/Optional.h +++ b/folly/Optional.h @@ -54,6 +54,7 @@ * } */ #include +#include #include #include #include @@ -418,3 +419,16 @@ template bool operator> (const V& other, const Optional&) = delete; /////////////////////////////////////////////////////////////////////////////// } // namespace folly + +// Allow usage of Optional in std::unordered_map and std::unordered_set +FOLLY_NAMESPACE_STD_BEGIN +template +struct hash> { + size_t operator()(folly::Optional const& obj) const { + if (!obj.hasValue()) { + return 0; + } + return hash::type>()(*obj); + } +}; +FOLLY_NAMESPACE_STD_END diff --git a/folly/test/OptionalTest.cpp b/folly/test/OptionalTest.cpp index 4a0ef9b3..3968040f 100644 --- a/folly/test/OptionalTest.cpp +++ b/folly/test/OptionalTest.cpp @@ -18,14 +18,14 @@ #include #include -#include -#include #include #include +#include #include #include +#include +#include -#include #include using std::unique_ptr; @@ -545,4 +545,12 @@ TEST(Optional, TriviallyDestructible) { EXPECT_TRUE(std::is_trivially_destructible>::value); EXPECT_FALSE(std::is_trivially_destructible>::value); } + +TEST(Optional, Hash) { + // Test it's usable in std::unordered map (compile time check) + std::unordered_map, Optional> obj; + // Also check the std::hash template can be instantiated by the compiler + std::hash>()(none); + std::hash>()(3); +} }