Given the following program
#include <boost/program_options.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace std;
namespace po = boost::program_options;
int main(int argc, const char *argv[]) {
try {
po::options_description global("Global options");
global.add_options()
("x", po::value<int>()->required(), "The required x value");
po::variables_map args;
// shouldn't this throw an exception, when --x is not given?
po::store(po::parse_command_line(argc, argv, global), args);
// throws bad_any_cast
cout << "x=" << args["x"].as<int>() << endl;
} catch (const po::error& e) {
std::cerr << e.what() << endl;
}
cin.ignore();
return 0;
}
X is required but given an empty command line parse_command_line doesn't throw an exception. So it crashs, when I access x via args["x"]. I got bad_any_cast instead.
Calling boost::program_options::store, as the name implies, only stores the options from the first parameter (which is a boost::program_options::basic_parsed_options) in the map passed as the second parameter. To run the required checks and get the exception you expect you have to also call boost::program_options::notify explicitly:
po::store(po::parse_command_line(argc, argv, global), args);
po::notify(args);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With