jarro2783 / cxxopts

Lightweight C++ command line option parser

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

eyalroz opened this issue · comments

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.

That sounds pretty reasonable.

@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.

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>