From d022256a4136234d742e3178d31948b5f88bc0f6 Mon Sep 17 00:00:00 2001 From: randomdan Date: Sun, 15 Sep 2013 12:43:27 +0000 Subject: Allow instance registration to occur with different key types --- project2/common/instanceStore.h | 103 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 project2/common/instanceStore.h (limited to 'project2/common/instanceStore.h') diff --git a/project2/common/instanceStore.h b/project2/common/instanceStore.h new file mode 100644 index 0000000..c61ccfe --- /dev/null +++ b/project2/common/instanceStore.h @@ -0,0 +1,103 @@ +#ifndef INSTANCESTORE_H +#define INSTANCESTORE_H + +#include +#include +#include +#include +#include + +/// A static collection of any type, specifically with automatically cleaned up storage of a function static variable +// which makes it safe to use in constructor functions. +template +class InstanceStore { + public: + static const StoreType & GetAll() + { + return *getInstances(); + } + + static void Add(const typename StoreType::value_type & p) + { + getInstances()->insert(p); + } + + template + static void Remove(const EraseByType & p) + { + getInstances()->erase(p); + prune(); + } + + static void OnEach(const boost::function & func) + { + BOOST_FOREACH(const auto & l, GetAll()) { + try { + func(l.get()); + } + catch (...) { + } + } + prune(); + } + + static void OnAll(const boost::function & func) + { + BOOST_FOREACH(const auto & l, GetAll()) { + try { + func(l.get()); + } + catch (...) { + } + } + prune(); + } + + private: + static void prune() + { + auto & ps = getInstances(); + if (ps->empty()) { + delete ps; + ps = NULL; + } + } + + static StoreType * & getInstances() + { + static StoreType * instances = NULL; + if (!instances) { + instances = new StoreType(); + } + return instances; + } +}; + +/// Keyed collection of instances +template +class InstanceMap : public InstanceStore>> { + public: + typedef std::map> Store; + typedef typename Store::value_type Value; + + static void Add(const KeyType & k, Type * p) { + InstanceStore::Add(Value(k, boost::shared_ptr(p))); + } + + static void Add(const KeyType & k, const boost::shared_ptr & p) { + InstanceStore::Add(Value(k, p)); + } + + template static boost::shared_ptr Get(const KeyType & n) + { + return safeMapLookup(InstanceStore::GetAll(), n); + } +}; + +/// Anonymous collection of instances +template +class InstanceSet : public InstanceStore>> { +}; + +#endif + -- cgit v1.2.3