]> git.tdb.fi Git - libs/datafile.git/commitdiff
Add find functions to Collection
authorMikko Rasa <tdb@tdb.fi>
Wed, 30 Dec 2020 16:40:48 +0000 (18:40 +0200)
committerMikko Rasa <tdb@tdb.fi>
Wed, 30 Dec 2020 16:40:48 +0000 (18:40 +0200)
source/collection.cpp
source/collection.h

index 129c0a84f76808c14f0a8164b853e0c56d6ccb97..6d7306357712c2b737f9ff5d8232a6888b5daffb 100644 (file)
@@ -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<const Variant *> *vars, list<string> *names, const CollectionItemTypeBase &type, bool include_sources) const
index d0e8a1a8bb9b25c636ab23a8c1e4bbdcfa5c04a7..87af3a2c2c606cde35d00abd8a20bf092744e19d 100644 (file)
@@ -135,8 +135,27 @@ public:
                return extract<NCT>(get_var(name, get_type<NCT>(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<typename T>
+       T *find(const std::string &name) const
+       {
+               ItemMap::const_iterator i = items.find(name);
+               return (i!=items.end() ? extract<typename RemoveConst<T>::Type>(i->second) : 0);
+       }
+
+       template<typename T>
+       T *find(const std::string &name)
+       {
+               typedef typename RemoveConst<T>::Type NCT;
+               const Variant *var = find_var(name, get_type<NCT>(name));
+               return (var ? &extract<NCT>(*var) : 0);
+       }
+
 private:
        const Variant &get_var(const std::string &, const CollectionItemTypeBase *);
+       const Variant *find_var(const std::string &, const CollectionItemTypeBase *);
 
        template<typename T>
        T &extract(const Variant &var) const;