29

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?

a06e
  • 18,594
  • 33
  • 93
  • 169
  • 1
    Possible duplicate of [boost-program-options: notifier for options with no value](https://stackoverflow.com/questions/7174781/boost-program-options-notifier-for-options-with-no-value) – ead Aug 28 '18 at 09:43

2 Answers2

42

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

sshannin
  • 2,767
  • 1
  • 22
  • 25
  • 2
    Centos 7.4, boost 1.53, aarch64. flag is always false, vm.count("flag") is always 1 despite any options change.The method below without bool_switch is correctly working with vm.count. – dE fENDER Jun 28 '18 at 14:12
  • The option below will accept a parameter. For example the command line "... -f 42" will take '42' as a value. The 42 could represent some other positional. See: [bool_switch always true](https://stackoverflow.com/questions/32150230/boost-program-options-bool-always-true). – artless noise Dec 21 '20 at 14:50
11

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.

user1810087
  • 5,146
  • 1
  • 41
  • 76