Commit 20f47e6c authored by Shai Szulanski's avatar Shai Szulanski Committed by Facebook GitHub Bot

Template get_optional on Optional type

Summary: Allows use with std::optional when available

Reviewed By: WillerZ

Differential Revision: D25618828

fbshipit-source-id: 3e039406ff1e885fd1767148b907635b23f7a88b
parent 2a41f3f0
......@@ -98,15 +98,18 @@ typename Map::mapped_type& get_or_throw(
* Given a map and a key, return a Optional<V> if the key exists and None if the
* key does not exist in the map.
*/
template <class Map, typename Key = typename Map::key_type>
folly::Optional<typename Map::mapped_type> get_optional(
template <
template <typename> class Optional = folly::Optional,
class Map,
typename Key = typename Map::key_type>
Optional<typename Map::mapped_type> get_optional(
const Map& map,
const Key& key) {
auto pos = map.find(key);
if (pos != map.end()) {
return folly::Optional<typename Map::mapped_type>(pos->second);
return Optional<typename Map::mapped_type>(pos->second);
} else {
return folly::none;
return {};
}
}
......
......@@ -98,6 +98,14 @@ TEST(MapUtil, get_optional_path_mixed) {
EXPECT_TRUE(get_optional(m, "a"));
}
TEST(MapUtil, get_optional_std) {
std::map<int, int> m;
m[1] = 2;
EXPECT_TRUE(get_optional<std::optional>(m, 1).has_value());
EXPECT_EQ(2, get_optional<std::optional>(m, 1).value());
EXPECT_FALSE(get_optional<std::optional>(m, 2).has_value());
}
TEST(MapUtil, get_ref_default) {
std::map<int, int> m;
m[1] = 2;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment