Boost program options bool always True

Using the program options, I check for valid combinations of arguments. But for some reason, the gpu argument is bool, and it is always true, regardless of whether it is set to false on the command line. Is there a way in which the gpu parameter can be false if I specify it on the command line? I want to be able to create a bool variable that represents if the option was used on the command line.

Also, I could not find documentation on count () for map_ variables. Is this a std :: map function?

Partial Code:

namespace po = boost::program_options;
po::options_description desc("Allowed Options");
desc.add_options()
  ("help,h", "Produce help message")
  ("remove_database,r",po::value<std::vector<std::string>>
    (&remove_database),
    "Remove a pre-built database, provide a name(s) of the database")
  ("gpu,u", po::bool_switch()->default_value(false),
    "Use GPU? Only for specific algorithms");

po::variables_map vm;
po::store(po::parse_command_line(argc,argv,desc),vm);
po::notify(vm);

//Processing Cmd Args
bool help           = vm.count("help");
bool remove         = vm.count("remove_database");
bool gpu            = vm.count("gpu");

test(help,"help");
test(remove, "remove");
test(gpu, "gpu");

.....
void test(bool var1, std::string var2){
  if(var1)
    std::cout << var2 << " is active " << std::endl;
 else
    std::cout << var2 << " is not active " << std::endl;

Output:

$./a.out -r xx -u off
remove is active 
gpu is active
$./a.out -r xx -u false
remove is active 
gpu is active
+4
source share
3 answers

bool_switch. false, ->default_value(false). , -u --gpu true. , .

. .

+5

, (*) count() 1 bool_switch. , :

bool help           = vm.count("help");

:

bool help           = vm["help"].as<bool>();

"" (*):

bool help           = vm.count("help") ? vm["help"].as<bool>() : false;

(*) , .

0

Although I did not directly answer the question that the OP spoke about, I think this is an important note. According to the boost_options spec spec program , regardless of your default value, when you specify an option from the command line, it always switches the switch totrue

So, if you use default_value(true)for bool_switch(), you cannot turn it off ...

0
source

All Articles