Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost program_options on/off flag

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?

like image 945
Barry Avatar asked Oct 16 '15 13:10

Barry


1 Answers

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))
    ;
like image 163
Barry Avatar answered Sep 21 '22 05:09

Barry