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

becko picture becko · May 16, 2014 · Viewed 11.6k times · Source

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?

Answer

sshannin picture sshannin · May 16, 2014

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