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

Unexpected behavior with add_flag and std::optional<bool> #694

Closed
sg-james opened this issue Jan 5, 2022 · 2 comments
Closed

Unexpected behavior with add_flag and std::optional<bool> #694

sg-james opened this issue Jan 5, 2022 · 2 comments

Comments

@sg-james
Copy link

sg-james commented Jan 5, 2022

Using a recent (2021-12-27) 9ec0ba7 build, under msvc14.1x64 (2017)

I want to represent a std::optional<bool> flag so I tried

std::optional<bool> opt_bool;
CLI::App app = ...
assert(opt_bool.has_value() == false); 
CLI::Option* opt = app.add_flag("--flag,!--no-flag", opt_bool, "My flag desc.");
assert(opt_bool.has_value() == false); // incorrectly (to me) is true

but opt_bool.has_value() is always true after add_flag(..)

I can work around this via

  1. using opt->count() > 0 to reset the optional or
auto callback =  [&opt_bool](int value){
	if (value == 1) opt_bool = true;
	else if (value == 2) opt_bool = false;
};
CLI::Option* opt = app.add_flag("--flag{1},--no-flag{2}", callback, "My flag desc.");

but was wondering if the first approach was meant to work as I had hoped?

Here's a simple project that demonstrates it: https://godbolt.org/z/cxzaY3o3s

@phlptp
Copy link
Collaborator

phlptp commented Jan 10, 2022

let me take a look, not sure I have tried anything with an optional bool

@phlptp
Copy link
Collaborator

phlptp commented Jan 10, 2022

I did verify the behavior you were seeing, has to do with the bool being in a wrapper, so the field is interpreted as an integer in the flag which implies a counting of the number flags for historical reasons and to support some particular use cases. In any case as part of that it assigns a zero to the variable. I am looking into possible solutions.

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