p-ranav/argparse

Unexpected hidden flag / default_value interaction

sgoth opened this issue · 3 comments

app.add_argument("--port").nargs(1).default_value(1234).flag().hidden();
// ...
app.get<int32_t>("--port");

throws bad any_cast as if there was no default_value defined

app.add_argument("--port").flag().hidden().nargs(1).default_value(1234);
// ...
app.get<int32_t>("--port");

works as expected.

v3.1 with gcc 14.2

Hi @sgoth,

  • It's expected to have bad any_cast in first scenario as flag function with override default_value object's value to true and when you try to cast it back to int32_t make sense to get that error and vice versa for the second scenario.
// This is shorthand for:
  //   program.add_argument("foo")
  //     .default_value(false)
  //     .implicit_value(true)
  Argument &flag() {
    default_value(false);
    implicit_value(true);
    return *this;
  } 

Hi @p-ranav,
You can close the issue.

Thanks for clarifying.
No idea why i thought flag() is part of the hidden() feature... 🤦🏻‍♂️