【发布时间】:2016-10-08 12:01:37
【问题描述】:
我想使用 boost_program_options 创建一个位置列表程序选项,该选项不允许命名程序选项(如 --files)。
我有以下sn-p的代码:
#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include <vector>
namespace po = boost::program_options;
int main(int argc, const char* argv[]) {
po::options_description desc("Allowed options");
desc.add_options()("help", "produce help message")
( "files", po::value<std::vector<std::string>>()->required(), "list of files");
po::positional_options_description pos;
pos.add("files", -1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(desc).positional(pos).run(), vm);
po::notify(vm);
} catch(const po::error& e) {
std::cerr << "Couldn't parse command line arguments properly:\n";
std::cerr << e.what() << '\n' << '\n';
std::cerr << desc << '\n';
return 1;
}
if(vm.count("help") || !vm.count("files")) {
std::cout << desc << "\n";
return 1;
}
}
问题是我可以将文件列表读取为位置参数列表,如下所示:
./a.out file1 file2 file3
但不幸的是,我也喜欢这样(我想禁用它)
./a.out --files file1 file2 file3
问题还在于产生的帮助:
./a.out
Couldn't parse command line arguments properly:
the option '--files' is required but missing
Allowed options:
--help produce help message
--files arg list of files
所以我想要的场景会更像(os 相似):
./a.out
Couldn't parse command line arguments properly:
[FILES ...] is required but missing
Allowed options:
--help produce help message
--optionx some random option used in future
[FILE ...] list of files
从desc.add_option()(...) 中删除files 选项后,它停止工作,所以我相信我需要它。
【问题讨论】:
-
为什么需要移除使用命名参数指定输入文件的能力?它对任何东西都没有害处,那么为什么要竭尽全力禁用它呢?
-
@DanMašek 我相信用户并不太清楚,因为这两种方式都可以成为有效的输入策略(我特别想要一种并且有帮助来支持它)
-
好的。那里有在我看来侵入性最小的解决方案。它仍然允许位置选项分散在整个参数列表中,但您可以轻松添加更多验证以对其进行更多限制。
-
顺便说一句,我认为您应该更改标题以更好地反映您的问题的主体。这是一个艰难的问题,但是像“使用位置选项并禁止其显式变体”之类的东西可能会更好。
标签: c++ c++11 boost boost-program-options