【问题标题】:How to use boost::program_options to accept an optional flag?如何使用 boost::program_options 接受可选标志?
【发布时间】:2014-05-16 20:17:36
【问题描述】:

我需要实现一个可选标志,比如-f/--flag。由于这是一个标志,因此没有关联的值。在我的代码中,我只需要知道是否设置了标志。使用 boost::program_options 的正确方法是什么?

【问题讨论】:

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


【解决方案1】:

一个方便的方法是使用bool_switch 功能:

bool flag = false;

namespace po = boost::program_options;

po::options_description desc("options");

desc.add_options()
  ("flag,f", po::bool_switch(&flag), "description");
po::variables_map vm;
//store & notify

if (flag) {
  // do stuff
}

这比手动检查字符串更安全(字符串在整个定义中只使用一次)。

【讨论】:

  • Centos 7.4,提升 1.53,aarch64。 flag 始终为 false,vm.count("flag") 始终为 1,尽管有任何选项更改。下面没有 bool_switch 的方法可以正确使用 vm.count。
  • 下面的选项将接受一个参数。例如,命令行“... -f 42”将采用“42”作为值。 42 可以代表其他一些位置。请参阅:bool_switch always true
【解决方案2】:

照常使用,但没有任何价值:

boost::program_options::options_description od("allowed options");
od.add_options()
    ("flag,f", "description");

po::variables_map vm;
// store/ notify vm
if (vm.count("flag")) {
    // flag is set
}

Getting Started 选项帮助为例。

【讨论】:

    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多