鉴于以下计划
#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是必需的,但是给定一个空命令行parse_command_line
不会抛出异常。当我通过x
访问args["x"]
时,它就会崩溃。我改为bad_any_cast
。
答案 0 :(得分:2)
顾名思义,调用boost::program_options::store
仅存储作为第二个参数传递的地图中第一个参数(即boost::program_options::basic_parsed_options
)的选项。要运行所需的检查并获得异常,您必须明确地调用boost::program_options::notify
:
po::store(po::parse_command_line(argc, argv, global), args);
po::notify(args);