jarro2783 / cxxopts

Lightweight C++ command line option parser
MIT License
4.25k stars 590 forks source link

Support the use of std::optional's in cxxopts::ParseResult::as() #383

Open eyalroz opened 1 year ago

eyalroz commented 1 year ago

Suppose I define a non-boolean option of type T, without a default value, using cxxopts.

I can't obtain this option using just cxxopts::ParseResults::as<T>() - because that might throw. Instead, I have to first use count(), like in the README example code:

if (result.count("bar"))
  bar = result["bar"].as<std::string>();

This is somewhat redundant. Why do I have to say "bar" twice? ... instead, I should be able to write:

auto bar = result["bar"].as<std::optional<std::string>>()

and get an optional which is nullopt if bar wasn't specified, and a boxed actual string if it was.

Bonus points if you support std::experimental::optional when C++14 is used.

jarro2783 commented 1 year ago

That sounds pretty reasonable.

eyalroz commented 1 year ago

@jarro2783 : An alternative, or an addition, to this, which would be "breaking", is changing as<T> so that it always returns an optional<T>, and never throws.

kwaegel commented 1 year ago

A non-breaking change would be adding get<T>() that returns an optional<T>. Combine this with operator[] and you could have some very compact syntax:

opts.get<std::string>("key"); // returns std::optional<std::string>