【发布时间】:2010-10-04 18:59:02
【问题描述】:
考虑以下从 boost 程序选项 examples 中采用的简单程序
#include <boost/program_options.hpp>
#include <boost/version.hpp>
#include <iostream>
int
main( int argc, char** argv )
{
namespace po = boost::program_options;
po::options_description desc("Options");
unsigned foo;
desc.add_options()
("help,h", "produce help message")
("foo", po::value(&foo), "set foo")
;
po::variables_map vm;
try {
po::store(
po::parse_command_line( argc, argv, desc ),
vm
);
po::notify( vm );
if ( vm.count("help") ) {
std::cout << desc << "\n";
std::cout << "boost version: " << BOOST_LIB_VERSION << std::endl;
}
} catch ( const boost::program_options::error& e ) {
std::cerr << e.what() << std::endl;
}
}
以下行为符合预期:
samm$ ./a.out -h
Options:
-h [ --help ] produce help message
--foo arg set foo
boost version: 1_44
samm$ ./a.out --help
Options:
-h [ --help ] produce help message
--foo arg set foo
boost version: 1_44
samm$ ./a.out --foo 1
samm$ ./a.out --asdf
unknown option asdf
samm$
但是,当我引入位置参数时,我很惊讶,它没有被标记为错误
samm$ ./a.out foo bar baz
samm$
为什么boost::program_options::too_many_positional_options_error没有抛出异常?
【问题讨论】:
-
我的猜测是,除非有前导
-或--,否则事物将被视为参数,而不是选项。 -
@Arun,该行为在文档中并未明确明确。我在下面的答案中找到了一个解决方案,尽管它对我来说似乎仍然违反直觉。
标签: c++ boost boost-program-options