From fb94876de2cd4e832532ee6c77dc114ce14f3279 Mon Sep 17 00:00:00 2001 From: fbraem Date: Tue, 19 Feb 2013 22:38:00 +0100 Subject: [PATCH] Add a get method that doesn't throw, but returns a default argument instead --- MongoDB/include/Poco/MongoDB/Document.h | 26 +++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/MongoDB/include/Poco/MongoDB/Document.h b/MongoDB/include/Poco/MongoDB/Document.h index 6f941a379..436428a3f 100644 --- a/MongoDB/include/Poco/MongoDB/Document.h +++ b/MongoDB/include/Poco/MongoDB/Document.h @@ -141,6 +141,32 @@ public: } } + + template + T get(const std::string& name, const T& def) const + /// Returns the element with the given name and tries to convert + /// it to the template type. When the element is not found, or + /// has the wrong type, the def argument will be returned. + { + Element::Ptr element = get(name); + if ( element.isNull() ) + { + return def; + } + + if ( ElementTraits::TypeId == element->type() ) + { + ConcreteElement* concrete = dynamic_cast* >(element.get()); + if ( concrete != NULL ) + { + return concrete->value(); + } + } + + return def; + } + + Element::Ptr get(const std::string& name) const; /// Returns the element with the given name. /// An empty element will be returned when the element is not found.