Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 689
becko Avatar asked May 16 '14 20:05

becko


2 Answers

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).

like image 195
sshannin Avatar answered Oct 23 '22 00:10

sshannin


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.

like image 10
user1810087 Avatar answered Oct 23 '22 01:10

user1810087