How to use boost::program_options to accept an optional flag?

喜夏-厌秋 提交于 2019-12-04 16:07:50

问题


I need to implement an optional flag, say -f/--flag. Since this is a flag, there is no value associated. In my code I only need to know whether the flag was set or not. What's the proper way to do this using boost::program_options?


回答1:


A convenient way to do this is with the bool_switch functionality:

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
}

This is safer than manually checking for the string (string only used once in whole definition).




回答2:


Use it as usual but without any value:

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
}

See the Getting Started option help as an example.



来源:https://stackoverflow.com/questions/23703890/how-to-use-boostprogram-options-to-accept-an-optional-flag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!