From: Martin Quinson Date: Fri, 30 Mar 2018 22:56:58 +0000 (+0200) Subject: config::Flag: allow to pass a map of the valid values X-Git-Tag: v3.20~570 X-Git-Url: http://info.iut-bm.univ-fcomte.fr/pub/gitweb/simgrid.git/commitdiff_plain/36b1fa831a191c389b1c907bfa35655b4283f06d config::Flag: allow to pass a map of the valid values --- diff --git a/include/xbt/config.hpp b/include/xbt/config.hpp index 236d87f962..f773739c86 100644 --- a/include/xbt/config.hpp +++ b/include/xbt/config.hpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include +#include namespace simgrid { namespace config { @@ -152,7 +154,32 @@ bindFlag(T& value, const char* name, const char* description, } )); } - +template +typename std::enable_if()(std::declval()))>::value, void>::type +bindFlag(T& value, const char* name, const char* description, std::map valid_values, F callback) +{ + declareFlag(name, description, value, + std::function([&value, name, valid_values, callback](const T& val) { + callback(val); + bool found = false; + for (auto kv : valid_values) { + if (kv.first == val) + found = true; + } + if (not found || std::string(val) == "help") { + std::string mesg; + if (std::string(val) == "help") + mesg = std::string("\nPossible values for option ") + name + ":\n"; + else + mesg = std::string("\nInvalid value '") + val + "' for option " + name + ". Possible values:\n"; + for (auto kv : valid_values) + mesg += " - '" + std::string(kv.first) + "': " + kv.second + + (kv.first == value ? " <=== DEFAULT" : "") + "\n"; + xbt_die("%s", mesg.c_str()); + } + value = std::move(val); + })); +} /** Bind a variable to configuration flag * *

@@ -202,12 +229,24 @@ public:
     simgrid::config::bindFlag(value_, name, desc);
   }
 
+  /* A constructor accepting a callback that will be passed the parameter.
+   * It can either return a boolean (informing whether the parameter is valid), or returning void.
+   */
   template
   Flag(const char* name, const char* desc, T value, F callback) : value_(value)
   {
     simgrid::config::bindFlag(value_, name, desc, std::move(callback));
   }
 
+  /* A constructor accepting a map of valid values -> their description,
+   * and producing an informative error message when an invalid value is passed, or when help is passed as a value.
+   */
+  template 
+  Flag(const char* name, const char* desc, T value, std::map valid_values, F callback) : value_(value)
+  {
+    simgrid::config::bindFlag(value_, name, desc, std::move(valid_values), std::move(callback));
+  }
+
   // No copy:
   Flag(Flag const&) = delete;
   Flag& operator=(Flag const&) = delete;