From ae1e251c5f3287701f5bb2b22ce0a9a1580ddfc7 Mon Sep 17 00:00:00 2001 From: Ronen Friedman Date: Wed, 12 Mar 2025 04:26:54 -0500 Subject: [PATCH] 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 --- src/common/cmdparse.h | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/common/cmdparse.h b/src/common/cmdparse.h index d4a5c11398f05..70c6045c3bb16 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); } -- 2.39.5