Skip to content

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

@sg-james

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

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