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 value:
boost::program_options::options_description od("allowed options");
od.add_options()
("flag,f", "description");
// the other stuff
po::variables_map vm;
// store/ notify vm
if (vm.count("flag")) {
// do stuff
}
See the Getting Started option help for example.