p-ranav/argparse

Implicit template type of 'present' is misleading.

EddyXorb opened this issue · 0 comments

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.