X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Fcore%2Fmaputils.h;h=88f47cd367b60c3e85d72d075e59370971295c79;hp=8c642fb9c57a1f9acda6ba5ab2d0dc5311316306;hb=8223c2aabe26469b6c580a223555496c5c5c5df5;hpb=1e0abc3a49ade6a4fa1b38f744df070c40a87724 diff --git a/source/core/maputils.h b/source/core/maputils.h index 8c642fb..88f47cd 100644 --- a/source/core/maputils.h +++ b/source/core/maputils.h @@ -9,11 +9,17 @@ namespace Msp { namespace MapUtilsInternal { +/* This dummy struct is used to introduce a conversion, making the overloaded +operator below worse than the templated one provided in lexicalcast.h. */ +struct Any +{ + template + Any(const T &) { } +}; + /* This must be hidden in the internal namespace to avoid interfering with -other things. There may be problems if a key type has operator<< for ostream -but not LexicalConverter. */ -template -void operator<<(LexicalConverter &, const T &) +other things. */ +inline void operator<<(LexicalConverter &, Any) { } template @@ -22,7 +28,7 @@ static std::string stringify_key(const T &k) try { LexicalConverter conv((Fmt())); - conv< typename T::mapped_type &get_item(T &map, const typename T::key_type &key) { - typename T::iterator i = map.find(key); + auto i = map.find(key); if(i==map.end()) throw key_error(key); @@ -61,20 +67,35 @@ typename T::mapped_type &get_item(T &map, const typename T::key_type &key) template const typename T::mapped_type &get_item(const T &map, const typename T::key_type &key) { - typename T::const_iterator i = map.find(key); + auto i = map.find(key); if(i==map.end()) throw key_error(key); return i->second; } +template +D *get_item(const T &map, const typename T::key_type &key) +{ + return dynamic_cast(get_item(map, key)); +} + template -const typename T::iterator insert_unique(T &map, const typename T::key_type &key, const typename T::mapped_type &item) +typename T::iterator insert_unique(T &map, const typename T::key_type &key, const typename T::mapped_type &item) { if(map.count(key)) throw key_error(key); - return map.insert(typename T::value_type(key, item)).first; + return map.insert(std::make_pair(key, item)).first; +} + +template +void remove_existing(T &map, const typename T::key_type &key) +{ + if(!map.count(key)) + throw key_error(key); + + map.erase(key); } } // namespace Msp