return (pos != map.end() ? pos->second : dflt);
}
+/**
+ * Give a map and a key, return the value corresponding to the key in the map,
+ * or a given default value if the key doesn't exist in the map.
+ */
+template <
+ class Map,
+ typename Func,
+ typename = typename std::enable_if<std::is_convertible<
+ typename std::result_of<Func()>::type,
+ typename Map::mapped_type>::value>::type>
+typename Map::mapped_type
+get_default(const Map& map, const typename Map::key_type& key, Func&& dflt) {
+ auto pos = map.find(key);
+ return pos != map.end() ? pos->second : dflt();
+}
+
/**
* Given a map and a key, return the value corresponding to the key in the map,
* or throw an exception of the specified type.
return (pos != map.end() ? pos->second : dflt);
}
+/**
+ * Given a map and a key, return a reference to the value corresponding to the
+ * key in the map, or the given default reference if the key doesn't exist in
+ * the map.
+ */
+template <
+ class Map,
+ typename Func,
+ typename = typename std::enable_if<std::is_convertible<
+ typename std::result_of<Func()>::type,
+ const typename Map::mapped_type&>::value>::type>
+const typename Map::mapped_type& get_ref_default(
+ const Map& map,
+ const typename Map::key_type& key,
+ Func&& dflt) {
+ auto pos = map.find(key);
+ return (pos != map.end() ? pos->second : dflt());
+}
+
/**
* Given a map and a key, return a pointer to the value corresponding to the
* key in the map, or nullptr if the key doesn't exist in the map.
EXPECT_EQ(0, get_default(m, 3));
}
+TEST(MapUtil, get_default_function) {
+ std::map<int, int> m;
+ m[1] = 2;
+ EXPECT_EQ(2, get_default(m, 1, [] { return 42; }));
+ EXPECT_EQ(42, get_default(m, 2, [] { return 42; }));
+ EXPECT_EQ(0, get_default(m, 3));
+}
+
TEST(MapUtil, get_or_throw) {
std::map<int, int> m;
m[1] = 2;
const int i = 42;
EXPECT_EQ(2, get_ref_default(m, 1, i));
EXPECT_EQ(42, get_ref_default(m, 2, i));
+ EXPECT_EQ(std::addressof(i), std::addressof(get_ref_default(m, 2, i)));
+}
+
+TEST(MapUtil, get_ref_default_function) {
+ std::map<int, int> m;
+ m[1] = 2;
+ const int i = 42;
+ EXPECT_EQ(2, get_ref_default(m, 1, [&i]() -> const int& { return i; }));
+ EXPECT_EQ(42, get_ref_default(m, 2, [&i]() -> const int& { return i; }));
+ EXPECT_EQ(
+ std::addressof(i),
+ std::addressof(
+ get_ref_default(m, 2, [&i]() -> const int& { return i; })));
}
TEST(MapUtil, get_ptr) {