Skip to content

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

Closed

Description

@sg-james

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

Activity

  1. phlptp commented on Jan 10, 2022

    @phlptp
    Collaborator

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

  2. phlptp commented on Jan 10, 2022

    @phlptp
    Collaborator

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions