From: Mikko Rasa Date: Wed, 30 Dec 2020 16:40:48 +0000 (+0200) Subject: Add find functions to Collection X-Git-Url: http://git.tdb.fi/?a=commitdiff_plain;h=b26fbba2bf5d53554325762b8022c501b3b8c8fb;p=libs%2Fdatafile.git Add find functions to Collection --- diff --git a/source/collection.cpp b/source/collection.cpp index 129c0a8..6d73063 100644 --- a/source/collection.cpp +++ b/source/collection.cpp @@ -17,10 +17,19 @@ Collection::~Collection() } const Variant &Collection::get_var(const string &name, const CollectionItemTypeBase *type) +{ + const Variant *var = find_var(name, type); + if(var) + return *var; + + throw key_error(name); +} + +const Variant *Collection::find_var(const string &name, const CollectionItemTypeBase *type) { ItemMap::iterator i = items.find(name); if(i!=items.end()) - return i->second; + return &i->second; if(type) { @@ -38,10 +47,11 @@ const Variant &Collection::get_var(const string &name, const CollectionItemTypeB if(!loaded && fallback) if(CollectionItemTypeBase *fb_type = fallback->get_type(*type)) if(fallback->get_status(name, *fb_type)) - return fallback->get_var(name, fb_type); + return fallback->find_var(name, fb_type); } - return get_item(items, name); + i = items.find(name); + return (i!=items.end() ? &i->second : 0); } void Collection::gather_items(vector *vars, list *names, const CollectionItemTypeBase &type, bool include_sources) const diff --git a/source/collection.h b/source/collection.h index d0e8a1a..87af3a2 100644 --- a/source/collection.h +++ b/source/collection.h @@ -135,8 +135,27 @@ public: return extract(get_var(name, get_type(name))); } + /** Finds a typed object in the collection. Returns null if the name does + not exist. Throws if the name exists but the object is of an incorrect + type. */ + template + T *find(const std::string &name) const + { + ItemMap::const_iterator i = items.find(name); + return (i!=items.end() ? extract::Type>(i->second) : 0); + } + + template + T *find(const std::string &name) + { + typedef typename RemoveConst::Type NCT; + const Variant *var = find_var(name, get_type(name)); + return (var ? &extract(*var) : 0); + } + private: const Variant &get_var(const std::string &, const CollectionItemTypeBase *); + const Variant *find_var(const std::string &, const CollectionItemTypeBase *); template T &extract(const Variant &var) const;