diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index e533199..553ed4b 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -719,11 +719,11 @@ namespace cxxopts if (m_result) { - copy = std::make_shared(m_store); + copy = std::make_shared(); } else { - copy = std::make_shared(); + copy = std::make_shared(m_store); } copy->m_default = m_default; @@ -969,6 +969,17 @@ namespace cxxopts return m_count; } + template + const T& + as() const + { +#ifdef CXXOPTS_NO_RTTI + return static_cast&>(*m_value).get(); +#else + return dynamic_cast&>(*m_value).get(); +#endif + } + private: void ensure_value(std::shared_ptr details) @@ -1006,7 +1017,7 @@ namespace cxxopts return riter->second.count(); } - const OptionDetails& + const OptionValue& operator[](const std::string& option) const { auto iter = m_options.find(option); @@ -1016,7 +1027,9 @@ namespace cxxopts throw option_not_present_exception(option); } - return *iter->second; + auto riter = m_results.find(iter->second); + + return riter->second; } private: @@ -1448,9 +1461,10 @@ ParseResult::consume_positional(std::string a) auto iter = m_options.find(*m_next_positional); if (iter != m_options.end()) { + auto& result = m_results[iter->second]; if (!iter->second->value().is_container()) { - if (iter->second->count() == 0) + if (result.count() == 0) { add_to_option(*m_next_positional, a); ++m_next_positional; diff --git a/test/options.cpp b/test/options.cpp index 6d11427..e78fffe 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -219,6 +219,24 @@ TEST_CASE("Empty with implicit value", "[implicit]") REQUIRE(result["implicit"].as() == ""); } +TEST_CASE("Parse into a reference", "[reference]") +{ + int value = 0; + + cxxopts::Options options("into_reference", "parses into a reference"); + options.add_options() + ("ref", "A reference", cxxopts::value(value)); + + Argv av({"into_reference", "--ref", "42"}); + + auto argv = av.argv(); + auto argc = av.argc(); + + auto result = options.parse(argc, argv); + CHECK(result.count("ref") == 1); + CHECK(value == 42); +} + TEST_CASE("Integers", "[options]") { cxxopts::Options options("parses_integers", "parses integers correctly"); @@ -236,6 +254,7 @@ TEST_CASE("Integers", "[options]") REQUIRE(result.count("positional") == 6); auto& positional = result["positional"].as>(); + REQUIRE(positional.size() == 6); CHECK(positional[0] == 5); CHECK(positional[1] == 6); CHECK(positional[2] == -6);