我想做一個位置,列表程序選項boost_program_options
,不允許命名程序選項(如--files
)。如何添加描述到boost :: program_options的位置選項?
我有下面的代碼片段:
#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
這個問題也是在yie LDS:
./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我相信用戶不太清楚,因爲這允許兩種方式成爲有效的輸入策略(我特別希望只有一種策略並且有幫助支持它) – Patryk
好的。在你看來,我認爲最不具侵略性的解決方案。它仍然允許位置選項分散在整個參數列表中,但是您可以輕鬆地添加更多驗證來限制它。 –