Add ability to iterate through parsed options

Fixes #74.
This commit is contained in:
Jarryd Beck 2017-11-07 17:47:39 +11:00
parent f0406578bd
commit d74a2c65a5
2 changed files with 56 additions and 0 deletions

View File

@ -980,6 +980,42 @@ namespace cxxopts
size_t m_count = 0; size_t m_count = 0;
}; };
class KeyValue
{
public:
KeyValue(std::string key, std::string value)
: m_key(std::move(key))
, m_value(std::move(value))
{
}
const
std::string&
key() const
{
return m_key;
}
const std::string
value() const
{
return m_value;
}
template <typename T>
T
as() const
{
T result;
values::parse_value(m_value, result);
return result;
}
private:
std::string m_key;
std::string m_value;
};
class ParseResult class ParseResult
{ {
public: public:
@ -1018,6 +1054,12 @@ namespace cxxopts
return riter->second; return riter->second;
} }
const std::vector<KeyValue>&
arguments() const
{
return m_sequential;
}
private: private:
OptionValue& OptionValue&
@ -1059,6 +1101,8 @@ namespace cxxopts
std::vector<std::string>::iterator m_next_positional; std::vector<std::string>::iterator m_next_positional;
std::unordered_set<std::string> m_positional_set; std::unordered_set<std::string> m_positional_set;
std::unordered_map<std::shared_ptr<OptionDetails>, OptionValue> m_results; std::unordered_map<std::shared_ptr<OptionDetails>, OptionValue> m_results;
std::vector<KeyValue> m_sequential;
}; };
class Options class Options
@ -1386,6 +1430,8 @@ ParseResult::parse_option
{ {
auto& result = m_results[value]; auto& result = m_results[value];
result.parse(value, arg); result.parse(value, arg);
m_sequential.emplace_back(value->long_name(), arg);
} }
inline inline

View File

@ -82,6 +82,16 @@ TEST_CASE("Basic options", "[options]")
CHECK(result.count("6") == 1); CHECK(result.count("6") == 1);
CHECK(result.count("p") == 2); CHECK(result.count("p") == 2);
CHECK(result.count("space") == 2); CHECK(result.count("space") == 2);
auto& arguments = result.arguments();
REQUIRE(arguments.size() == 7);
CHECK(arguments[0].key() == "long");
CHECK(arguments[0].value() == "");
CHECK(arguments[0].as<bool>() == true);
CHECK(arguments[1].key() == "short");
CHECK(arguments[2].key() == "value");
CHECK(arguments[3].key() == "av");
} }
TEST_CASE("Short options", "[options]") TEST_CASE("Short options", "[options]")