Skip to content

Commit ae1e251

Browse files
committed
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 <[email protected]>
1 parent 6e4da22 commit ae1e251

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/common/cmdparse.h

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,34 @@ T cmd_getval_or(const cmdmap_t& cmdmap, std::string_view k,
102102
const V& defval)
103103
{
104104
auto found = cmdmap.find(k);
105-
if (found == cmdmap.end()) {
105+
if (found == cmdmap.cend()) {
106106
return T(defval);
107107
}
108108
try {
109-
return boost::get<T>(cmdmap.find(k)->second);
109+
return boost::get<T>(found->second);
110+
} catch (boost::bad_get&) {
111+
throw bad_cmd_get(k, cmdmap);
112+
}
113+
}
114+
115+
/**
116+
* with default, to be used when the parameter type (which matches the type of the
117+
* 'default' object) is not one of the limited set of parameters type.
118+
* Added to support "safe types" - typed wrappers "around" simple types (e.g.
119+
* shard_id_t which is a structure holding one int8_t), without requiring the
120+
* user to specify the default in the 'internal type'.
121+
*
122+
* Throws if the key is found, but the type is not the expected one.
123+
*/
124+
template <typename CMD_TYPE, typename T>
125+
T cmd_getval_cast_or(const cmdmap_t& cmdmap, std::string_view k, T defval)
126+
{
127+
auto found = cmdmap.find(k);
128+
if (found == cmdmap.cend()) {
129+
return defval;
130+
}
131+
try {
132+
return T(boost::get<CMD_TYPE>(found->second));
110133
} catch (boost::bad_get&) {
111134
throw bad_cmd_get(k, cmdmap);
112135
}

0 commit comments

Comments
 (0)