我有一个使用boost v1.45.0程序选项的Visual Studio2008 C++应用程序。
我希望能够解析如下所示的命令行选项:foo.exe -x 1,2, 4-7,这样它就可以生成值为1、2、4、5、6、7的std::vector< int >。因此,我编写了一个自定义验证器:
typedef std::vector< int > IDList;
void validate( boost::any& v, const std::vector< std::string >& tokens, IDList*, int )
{
// Never gets here
}
int _tmain( int argc, _TCHAR* argv[] )
{
IDList test_case_ids;
po::options_description desc( "Foo options" );
desc.add_options()
("id,x", po::value< IDList >(), "Specify a single ID or a range of IDs as shown in the following command line: foo.exe -x10,12, 15-20")
;
po::variables_map vm;
try
{
po::store( po::parse_command_line( argc, argv, desc ), vm );
po::notify( vm );
}
catch( const std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cout << desc << std::endl;
return 1;
}
return 0;
}但是,我从来没有得到我的自定义验证器代码。我在parse_command_line中总是得到一个异常,消息是:in option 'id': invalid option value。
我需要做些什么才能让它像预期的那样工作?
谢谢,PaulH
发布于 2011-02-26 09:41:05
作为boost::program_options::value_semantic的typedef std::vector<int>不能按您期望的方式工作,因为vector有一个指向程序选项库的special meaning:
该库为向量提供了特殊支持--可以多次指定该选项,所有指定的值都将被收集到一个向量中。
这意味着类似这样的描述
typedef std::vector< int > IDList;
po::options_description desc( "Foo options" );
desc.add_options()
("id,x", po::value< IDList >(), "list of IDs")
;在给定以下命令行的情况下合并到单个std::vector<int>中
a.out --id 1 --id 2 --id 3 --id 4结果将是一个包含四个元素的std::vector。您需要定义一个特定的类型来使用自定义验证器,struct IDList是correct approach。
发布于 2011-02-26 01:43:20
您可以尝试编写自己的函数来解析命令行选项:
See here
您可以编写自己的解析器函数,例如reg_foo,并按如下方式使用它:
variables_map vm;
store(command_line_parser(argc, argv).options(desc).extra_parser(reg_foo)
.run(), vm);另请参阅随boost一起分发的示例代码,位于example/custom_syntax.cpp中
发布于 2011-02-26 03:51:56
问题在于IDList的定义。如果我更改定义以匹配regex.cpp示例中使用的magic_number类型,它就可以工作。
struct IDList
{
public:
std::vector< int > ids_;
IDList( std::vector< int > ids ) : ids_( ids ) {}
};我还没有研究为什么typedef会成为框架的问题,但这是可行的。
-PaulH
https://stackoverflow.com/questions/5120303
复制相似问题