p-ranav / argparse

Argument Parser for Modern C++
MIT License
2.59k stars 244 forks source link

Implicit template type of 'present' is misleading. #366

Open EddyXorb opened 2 months ago

EddyXorb commented 2 months ago

Say I have

int main(int argc, char** argv)
{
std::unique_ptr<argparse::ArgumentParser> parser =
    std::make_unique<argparse::ArgumentParser>("finland-course-optimization");
parser.add_argument("--number").scan<'i', int>()
parser.parse_args(argc,argv);

int n;
if (parser.present("number"))
   n = parser.get<int>("number");
}

This will compile. And crash during runtime with 'bad any cast'. If I omit the if and use 'get' directly, then it will parse correctly. Strange!

I lost one hour finding out that if I use 'present', there is default template argument 'std::string' that will throw the exception. To correct the above example, one has to write 'present("number")'.

In my opinion the default template argument is quite a trap and should be omitted if possible. Another possibility would be to work with constexpr type lists and avoid successful compilation if the type is wrongly specified. This would be the best approach in my opinion. It could perhaps be realized using enums for the arguments and magic_params.