diff --git a/CHANGELOG.md b/CHANGELOG.md index 94be76f..b030a15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ options. The project adheres to semantic versioning. * Only search for a C++ compiler in CMakeLists.txt. * Allow for exceptions to be disabled. +* Fix duplicate default options when there is a short and long option. ## 2.2 diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 8ff3946..0e1aa40 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1086,15 +1086,23 @@ namespace cxxopts parse_default(std::shared_ptr details) { ensure_value(details); + m_default = true; m_value->parse(); } size_t - count() const + count() const noexcept { return m_count; } + // TODO: maybe default options should count towards the number of arguments + bool + has_default() const noexcept + { + return m_default; + } + template const T& as() const @@ -1126,6 +1134,7 @@ namespace cxxopts std::shared_ptr m_value; size_t m_count = 0; + bool m_default = false; }; class KeyValue @@ -1989,7 +1998,7 @@ ParseResult::parse(int& argc, char**& argv) auto& store = m_results[detail]; - if(!store.count() && value.has_default()){ + if(value.has_default() && !store.count() && !store.has_default()){ parse_default(detail); } } diff --git a/test/options.cpp b/test/options.cpp index 8c3f23d..d110e01 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -315,8 +315,10 @@ TEST_CASE("Default values", "[default]") { cxxopts::Options options("defaults", "has defaults"); options.add_options() - ("default", "Has implicit", cxxopts::value() - ->default_value("42")); + ("default", "Has implicit", cxxopts::value()->default_value("42")) + ("v,vector", "Default vector", cxxopts::value>() + ->default_value("1,4")) + ; SECTION("Sets defaults") { Argv av({"implicit"}); @@ -327,6 +329,11 @@ TEST_CASE("Default values", "[default]") auto result = options.parse(argc, argv); CHECK(result.count("default") == 0); CHECK(result["default"].as() == 42); + + auto& v = result["vector"].as>(); + REQUIRE(v.size() == 2); + CHECK(v[0] == 1); + CHECK(v[1] == 4); } SECTION("When values provided") {