p-ranav / argparse

Argument Parser for Modern C++
MIT License
2.72k stars 250 forks source link

Subparser example snippet can't work #342

Open trick2011 opened 8 months ago

trick2011 commented 8 months ago

The following snippets can't work. It is given in the section Getting Argument and Subparser Instances

argparse::ArgumentParser program("test");

program.add_argument("--dir");
program.at("--dir").default_value(std::string("/home/user"));

program.add_subparser(argparse::ArgumentParser{"walk"});
program.at<argparse::ArgumentParser>("walk").add_argument("depth");

It proposes creating a temporary ArgumentParser instance and passing it to add_subparser. This can't work as add_subparser takes ArgumentParser &parser reference and adds it to m_subparsers which is a referencewrapper to the original object. std::list<std::reference_wrapper<ArgumentParser>> m_subparsers;

As such in my application the compiler complains with:

error: cannot bind non-const lvalue reference of type ‘argparse::ArgumentParser&’ to an rvalue of type ‘argparse::ArgumentParser’ 6 | program.add_subparser(argparse::ArgumentParser{"walk"});

I would agree that the intended behaviour is wanted. I see two 'easy' options, either by changing m_subparsers to be a copy of the passed subparser or keeping a separate copy when calling a copy-by-value variant of the add_subparser function.