【问题标题】:Handling unknown commands with the boost command line parser使用 boost 命令行解析器处理未知命令
【发布时间】:2013-07-31 16:28:22
【问题描述】:

我想处理(注意,不要以任何方式使用)未知选项。

所以有这样的:

http://www.boost.org/doc/libs/1_54_0/doc/html/program_options/howto.html#idp123440592

这可以用来收集和使用任何未知的选项,所以我可以这样做:

po::variables_map vm;
po::parsed_options parsed = po::command_line_parser(ac,av).options(desc).allow_unregistered().run();

{
  vector<string> to_pass_further = collect_unrecognized(parsed.options, po::include_positional);
  if (to_pass_further.size())
  {
    cout << "Unrecognized options:" << endl;
    for (auto i = to_pass_further.cbegin(); i != to_pass_further.cend(); ++i)
    {
      cout << std::left << std::setw(2) << ' ' << *i;
    return -1;
    }
  }
}

但由于我认为人们一直都在这样做,而图书馆应该处理我们一直在做的所有事情,所以我是否错过了一些更清洁的东西?

【问题讨论】:

  • 等等,你有一个函数可以在vector 中为你提供无法识别的选项,并且......你想让它更干净吗?确切地说,您认为这个更简洁的界面可以做什么?
  • @Yakk 在 po::command_line_parser 上(或者可能在 po::notify 调用上)喷出而不是基本上抛出异常。
  • 什么,在库中打印未本地化的错误消息?这似乎是个坏主意。

标签: c++ boost boost-program-options


【解决方案1】:
try
{
  po::options_description desc("Allowed options");

  desc.add_options()
    ("help,h", "produce help message")
    ("compression", po::value<int>()->required(), "set compression level")
    ;


  po::variables_map vm;
  po::store(po::parse_command_line(ac, av, desc), vm);
  po::notify(vm);
}
catch(std::exception& e)
{
  std::cerr << "Error: " << e.what() << "\n";
  return -1;
}
catch(...)
{
  std::cerr << "Unknown error!" << "\n";
  return -1;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2012-09-26
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    相关资源
    最近更新 更多