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

A parameter of type std::optional<std::vector<>> will only ever be populated with the last element in the list. #17

Closed
tfinnegan937 opened this issue May 28, 2023 · 1 comment

Comments

@tfinnegan937
Copy link

tfinnegan937 commented May 28, 2023

If you have an std::optional parameter containing an std::vector, you currently need to manually override the action in order to get it to behave properly.

If you input more than a single value for that argument, it will only ever insert a single value into the vector, and then continuously overwrite that one value.

Example code:

std::optional<std::vector<std::string>> my_optional_value = std::nullopt;

auto parser = argumentum::argument_parser();
auto params = argument_parser.params();

parser.config().program(argv[0]).description(
    "A dummy program."
);

params.add_parameter(my_optional_value, "--dummy", "-d")
    .help("A dummy value")
    .metavar("DUMMY")
    .minargs(1)
    .required(true);

assert(parser.parse_args(argc, argv, 1)); //Asserting here for the example. Just assume it parses successfully

for(auto it = my_optional_value.value().begin(); it != my_optional_value.value().end(); it++)
{
    std::cout << *it << std::endl;
}

Input:
-d A B C D

Output:
D

If I update the parameter by adding the following method invocation:

.action( [&]( auto& target, const std::string& value ) {
    if(!target.has_value())
    {
        target = std::make_optional<ArgumentList>(ArgumentList());
     }
    target.value().push_back(value);
} )

I get the output:
A
B
C
D

As such, it looks to me like the default action for an optional vector isn't appending anything to the vector, and is instead continuously overwriting the first value.

@mmahnic
Copy link
Owner

mmahnic commented Aug 30, 2023

@tfinnegan937 Thanks for the report. The behaviour was fixed in #18.

I wasn't going to support optional initially because I assumed one would look at the size() of a plain vector to see if the option was present, so I left this case unhandled. But after your report, it occurred to me that this could be useful for options with minargs(0). Now when an argument is an option without values, an optional gets a value, an empty vector. In previous versions, flagValue was added to the vector.

@mmahnic mmahnic closed this as completed Aug 30, 2023
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

2 participants