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

Reify values of optional arguments into std::optional #66

Closed
zhihaoy opened this issue Nov 27, 2019 · 1 comment · Fixed by #68
Closed

Reify values of optional arguments into std::optional #66

zhihaoy opened this issue Nov 27, 2019 · 1 comment · Fixed by #68

Comments

@zhihaoy
Copy link
Contributor

zhihaoy commented Nov 27, 2019

Semantically, an optional argument is "optional" to present. But currently, if default_value isn't set, an optional argument's "not presented" state is not representable. Attempting to access the state (value) will get a logic_error. Representing the "not presented" state is often necessary because the option's type may leave no value for a good default_value. For example, an empty string may be an valid argument to an option.

Python argparse has no such problem because any option may be None. Universally Nullable is a problem, but allowing None for specific types is adopted by many languages. In C++ it's std::optional<T>.

I suggest to add a program.present<T>("--option") API in addition to the existing program.get<T>("--option") API. The new API returns std::optional<T> by reifying T's possible values and the "not presented" state. Its usage looks like the following:

if (auto v = program.present<int>("-n")) {
  do_something_with(*v);
}

The name "present" is taken from Java's Optional.ifPresent. Bike-shedding is mildly welcome.

@p-ranav
Copy link
Owner

p-ranav commented Nov 27, 2019

Sounds good to me. Stands to reason.

zhihaoy added a commit to zhihaoy/argparse that referenced this issue Nov 30, 2019
zhihaoy added a commit to zhihaoy/argparse that referenced this issue Dec 1, 2019
zhihaoy added a commit to zhihaoy/argparse that referenced this issue Dec 1, 2019
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

Successfully merging a pull request may close this issue.

2 participants