Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
eyalroz opened this issue Dec 18, 2022 · 3 comments
Open

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

eyalroz opened this issue Dec 18, 2022 · 3 comments

Comments

@eyalroz
Copy link
Contributor

eyalroz commented Dec 18, 2022

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
Copy link
Owner

That sounds pretty reasonable.

@eyalroz
Copy link
Contributor Author

eyalroz commented Dec 21, 2022

@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
Copy link

kwaegel commented Oct 24, 2023

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants