util: add GetWithDef()

Looks up a value in a map and returns a found value or a default. This
mimicks Python's dict.get().

Because it is not possible in C++ to return None as default, the
returned value is wrapped in a InitState to tell the caller whether
the value was found.

Depends on the unified InitState template.
This commit is contained in:
Patrick Ohly 2012-09-13 17:13:19 +02:00
parent 53b72a035a
commit eefb631d28

View file

@ -415,6 +415,23 @@ template<class T> class InitState : public InitStateBase<T, boost::is_class<T>::
bool wasSet() const { return m_wasSet; }
};
/**
* Retrieve value if found in map, otherwise the
* default. wasSet() returns true only in the first case.
*/
template<class C> InitState<typename C::mapped_type>
GetWithDef(const C &map,
const typename C::key_type &key,
const typename C::mapped_type &def = boost::value_initialized<typename C::mapped_type>())
{
typename C::const_iterator it = map.find(key);
if (it != map.end()) {
return InitState<typename C::mapped_type>(it->second, true);
} else {
return InitState<typename C::mapped_type>(def, false);
}
}
/**
* a nop destructor which doesn't do anything, for boost::shared_ptr
*/