From: Mikko Rasa Date: Thu, 9 Jun 2011 13:02:55 +0000 (+0300) Subject: Add utility functions for getting an item from an std::map X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=commitdiff_plain;h=9519381422961a538a3ebbd1e6563d170215f14e Add utility functions for getting an item from an std::map --- diff --git a/source/core/maputils.cpp b/source/core/maputils.cpp new file mode 100644 index 0000000..4fcc8e2 --- /dev/null +++ b/source/core/maputils.cpp @@ -0,0 +1,12 @@ +#include +#include "maputils.h" + +using namespace std; + +namespace Msp { + +key_error::key_error(const type_info &t): + runtime_error(Debug::demangle(t.name())) +{ } + +} // namespace Msp diff --git a/source/core/maputils.h b/source/core/maputils.h new file mode 100644 index 0000000..1a7c0ae --- /dev/null +++ b/source/core/maputils.h @@ -0,0 +1,38 @@ +#ifndef MSP_CORE_MAPUTILS_H_ +#define MSP_CORE_MAPUTILS_H_ + +#include +#include + +namespace Msp { + +class key_error: public std::runtime_error +{ +public: + key_error(const std::type_info &); +}; + + +template +typename T::mapped_type &get_item(T &map, const typename T::key_type &key) +{ + typename T::iterator i = map.find(key); + if(i==map.end()) + throw key_error(typeid(T)); + + return i->second; +} + +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); + if(i==map.end()) + throw key_error(typeid(T)); + + return i->second; +} + +} // namespace Msp + +#endif