6

Using bool_switch, I can write a command line option to turn a flag on:

bool flag;

po::options_description options;
options.add_options()
    ("on", po::bool_switch(&flag)->default_value(false))
    ;

Where now ./a.out will have flag==false and ./a.out --on will have flag==true. But, for the purposes of being explicit, I would additionally like to add a command line option to turn flag off. Something like:

options.add_options()
    ("on", po::bool_switch(&flag)->default_value(false))
    ("off", po::anti_bool_switch(&flag)) // ????
    ;

Is there a way to do anti_bool_switch in the program_options library, or do I basically have to write a proxy bool reference?

Barry
  • 286,269
  • 29
  • 621
  • 977

2 Answers2

5

One thing I've been able to come up with (not sure if this is the best approach) is using implicit_value():

po::typed_value<bool>* store_bool(bool* flag, bool store_as)
{
    return po::value(flag)->implicit_value(store_as)->zero_tokens();
}

value will have to be initialized with the desired default, but otherwise this meets the desired functionality:

bool value = false;
options.add_options()
    ("on", store_bool(&value, true))
    ("off", store_bool(&value, false))
    ;
Barry
  • 286,269
  • 29
  • 621
  • 977
2

I am not sure your requirement makes sense. What happens if user types "./a.out --on --off"?

Otherwise, all you need is to ensure that you do not get an 'unrecognized option' message if user types "./a.out --off" and you will get the behaviour you want.

bool flag;
bool flag_off

po::options_description options;
options.add_options()
    ("on", po::bool_switch(&flag)->default_value(false))
    ("off", po::bool_switch(&flag_off)->default_value(false))    ;

...

if( flag_on && flag_off )
{
  cout << "nasty error" << endl; exit(1)
}
ravenspoint
  • 19,093
  • 6
  • 57
  • 103