From: Ronen Friedman Date: Wed, 12 Mar 2025 09:26:54 +0000 (-0500) Subject: common: add cmd_getval_cast_or() X-Git-Tag: v20.3.0~310^2~2 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=ae1e251c5f3287701f5bb2b22ce0a9a1580ddfc7;p=ceph.git common: add cmd_getval_cast_or() This slight variation of cmd_getval_or() can be used where the object type is different from the configuration item type (as when the object is a wrapper around an integer). It allows specifying the 'default' value in the object type. Signed-off-by: Ronen Friedman --- diff --git a/src/common/cmdparse.h b/src/common/cmdparse.h index d4a5c11398f..70c6045c3bb 100644 --- a/src/common/cmdparse.h +++ b/src/common/cmdparse.h @@ -102,11 +102,34 @@ T cmd_getval_or(const cmdmap_t& cmdmap, std::string_view k, const V& defval) { auto found = cmdmap.find(k); - if (found == cmdmap.end()) { + if (found == cmdmap.cend()) { return T(defval); } try { - return boost::get(cmdmap.find(k)->second); + return boost::get(found->second); + } catch (boost::bad_get&) { + throw bad_cmd_get(k, cmdmap); + } +} + +/** + * with default, to be used when the parameter type (which matches the type of the + * 'default' object) is not one of the limited set of parameters type. + * Added to support "safe types" - typed wrappers "around" simple types (e.g. + * shard_id_t which is a structure holding one int8_t), without requiring the + * user to specify the default in the 'internal type'. + * + * Throws if the key is found, but the type is not the expected one. + */ +template +T cmd_getval_cast_or(const cmdmap_t& cmdmap, std::string_view k, T defval) +{ + auto found = cmdmap.find(k); + if (found == cmdmap.cend()) { + return defval; + } + try { + return T(boost::get(found->second)); } catch (boost::bad_get&) { throw bad_cmd_get(k, cmdmap); }