* or throw an exception of the specified type.
*/
template <class E = std::out_of_range, class Map>
-typename Map::mapped_type get_or_throw(
- const Map& map, const typename Map::key_type& key,
+const typename Map::mapped_type& get_or_throw(
+ const Map& map,
+ const typename Map::key_type& key,
+ const std::string& exceptionStrPrefix = std::string()) {
+ auto pos = map.find(key);
+ if (pos != map.end()) {
+ return pos->second;
+ }
+ throw E(folly::to<std::string>(exceptionStrPrefix, key));
+}
+
+template <class E = std::out_of_range, class Map>
+typename Map::mapped_type& get_or_throw(
+ Map& map,
+ const typename Map::key_type& key,
const std::string& exceptionStrPrefix = std::string()) {
auto pos = map.find(key);
if (pos != map.end()) {
m[1] = 2;
EXPECT_EQ(2, get_or_throw(m, 1));
EXPECT_THROW(get_or_throw(m, 2), std::out_of_range);
+ EXPECT_EQ(&m[1], &get_or_throw(m, 1));
+ get_or_throw(m, 1) = 3;
+ EXPECT_EQ(3, get_or_throw(m, 1));
+ const auto& cm = m;
+ EXPECT_EQ(&m[1], &get_or_throw(cm, 1));
+ EXPECT_EQ(3, get_or_throw(cm, 1));
+ EXPECT_THROW(get_or_throw(cm, 2), std::out_of_range);
}
TEST(MapUtil, get_or_throw_specified) {