From 9519381422961a538a3ebbd1e6563d170215f14e Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 16:02:55 +0300 Subject: [PATCH] Add utility functions for getting an item from an std::map --- source/core/maputils.cpp | 12 ++++++++++++ source/core/maputils.h | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 source/core/maputils.cpp create mode 100644 source/core/maputils.h 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 -- 2.43.0