Commit 76717cb3dd23fe77ad5d8ba2b7479b3eecc719a1

Authored by Jesús González
Committed by jarro2783
1 parent 24162899

Add default "default" value to boolean options (#94)

* Add default "default" value of "false" to boolean options, therefore allowing to call result["boolOpt"].as<bool>() without throwing an exception.
include/cxxopts.hpp
... ... @@ -855,13 +855,13 @@ namespace cxxopts
855 855  
856 856 standard_value()
857 857 {
858   - set_implicit();
  858 + set_default_and_implicit();
859 859 }
860 860  
861 861 standard_value(bool* b)
862 862 : abstract_value(b)
863 863 {
864   - set_implicit();
  864 + set_default_and_implicit();
865 865 }
866 866  
867 867 std::shared_ptr<Value>
... ... @@ -873,8 +873,10 @@ namespace cxxopts
873 873 private:
874 874  
875 875 void
876   - set_implicit()
  876 + set_default_and_implicit()
877 877 {
  878 + m_default = true;
  879 + m_default_value = "false";
878 880 m_implicit = true;
879 881 m_implicit_value = "true";
880 882 }
... ...
test/options.cpp
... ... @@ -423,6 +423,9 @@ TEST_CASE(&quot;Booleans&quot;, &quot;[boolean]&quot;) {
423 423 ("bool", "A Boolean", cxxopts::value<bool>())
424 424 ("debug", "Debugging", cxxopts::value<bool>())
425 425 ("timing", "Timing", cxxopts::value<bool>())
  426 + ("noExplicitDefault", "No Explicit Default", cxxopts::value<bool>())
  427 + ("defaultTrue", "Timing", cxxopts::value<bool>()->default_value("true"))
  428 + ("defaultFalse", "Timing", cxxopts::value<bool>()->default_value("false"))
426 429 ("others", "Other arguments", cxxopts::value<std::vector<std::string>>())
427 430 ;
428 431  
... ... @@ -438,10 +441,16 @@ TEST_CASE(&quot;Booleans&quot;, &quot;[boolean]&quot;) {
438 441 REQUIRE(result.count("bool") == 1);
439 442 REQUIRE(result.count("debug") == 1);
440 443 REQUIRE(result.count("timing") == 1);
  444 + REQUIRE(result.count("noExplicitDefault") == 1);
  445 + REQUIRE(result.count("defaultTrue") == 1);
  446 + REQUIRE(result.count("defaultFalse") == 1);
441 447  
442 448 CHECK(result["bool"].as<bool>() == false);
443 449 CHECK(result["debug"].as<bool>() == true);
444 450 CHECK(result["timing"].as<bool>() == true);
  451 + CHECK(result["noExplicitDefault"].as<bool>() == false);
  452 + CHECK(result["defaultTrue"].as<bool>() == true);
  453 + CHECK(result["defaultFalse"].as<bool>() == false);
445 454  
446 455 REQUIRE(result.count("others") == 1);
447 456 }
... ...