解析位置参数
考虑以下从 boost 程序选项采用的简单程序 示例
#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
异常?
Consider the following trivial program adopted from the boost program options 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;
}
}
the following behavior is as expected:
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$
However, I was surprised when introducing a positional argument, it was not flagged as an error
samm$ ./a.out foo bar baz
samm$
Why is boost::program_options::too_many_positional_options_error
exception not thrown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我明确指示不支持位置选项时:
我得到了预期的行为:
when I explicitly indicate no positional options are supported:
I get the expected behavior: