CLI11
CLI11 copied to clipboard
improve documentation for custom converters/validators
I'd like to extend the library to support more option type.
I'd prefer to avoid to use lambdas or simply define functions to pass to add_option_function(). Rather I'd like to add code that will let the user simply write
date::year_month_day DateE;
add_option("-e,--date-e", DateE, "Return draw at date")->check(CLI::DateValidator);
Right now I wrote:
namespace date {
bool lexical_cast(const std::string &in, date::year_month_day &val)
{
return val.ok();
}
}
namespace CLI {
std::ostringstream &operator<<(std::ostringstream &in, date::year_month_day &val) {
in << val.year() << "-" << val.month() << "-" << val.day();
return in;
}
std::istringstream &operator>>(std::istringstream &in, date::year_month_day &val) {
std::chrono::time_point<std::chrono::system_clock, std::chrono::days> tp;
date::from_stream(in, "%Y-%m-%d", tp);
date::year_month_day t{floor<std::chrono::days>(tp)};
val = t;
return in;
}
namespace detail {
template<>
constexpr const char* type_name<year_month_day>() {
return "ymd [YYYY-mm-dd]";
}
} // end namespace deatil
} // end namespace CLI
but simply
std::istringstream &operator>>
doesn't get called at all. And dateE still cntain its default value.
What am I missing?
thanks
Well from what I can tell
namespace date {
bool lexical_cast(const std::string &in, date::year_month_day &val)
{
return val.ok();
}
}
would get called but doesn't do anything and returns true. So I think you would either need to make this function call the operator>> or just get rid of it and let CLI call it on the default lexical_cast
Thanks.
So then, what's the use of std::istringstream &operator>> if I'm going to do the conversion in lexical_cast? If I don't need to restrict the dates (or any other option type) do I need a validator, if the only thing I care is successful conversion?
If I had to implement a library extension I'd prefer to have << and >> operators that may come usefull, but If I comment out the lexical_cast I get:
static assertion failed: option object type must have a lexical cast overload or streaming input operator(>>) defined, if it is convertible from another type use the add_option<T, XC>(...) with XC being the known type
thanks again
You can try putting the overloaded streaming operators in the date namespace. The name lookup with header libraries is bit "questionable"/"confusing"
The purpose of a validator is to restrict what would otherwise be a valid conversion. If you want to allow all valid conversions then a validator is not necessary.
Thanks, it worked.
I'll do some experiments to get a better understanding of how things are working and try to write some meaningful commented examples to add to the documentation.