boost program_options on/off flag
Asked Answered
K

2

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?

Kohlrabi answered 16/10, 2015 at 13:33 Comment(0)
K
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))
    ;
Kohlrabi answered 16/10, 2015 at 14:30 Comment(0)
R
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)
}
Rickirickie answered 16/10, 2015 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.