Skip to content

Commit

Permalink
Throw in ParseResult::as when option isn't present
Browse files Browse the repository at this point in the history
  • Loading branch information
jarro2783 committed Nov 19, 2018
1 parent c713b44 commit 84feb4b
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ options. The project adheres to semantic versioning.
* Fix version numbering in CMakeLists.txt
* Remove unused declaration of the undefined `ParseResult::get_option`.
* Throw on invalid option syntax when beginning with a `-`.
* Throw in `as` when option wasn't present.

## 2.1.1

Expand Down
4 changes: 4 additions & 0 deletions include/cxxopts.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,10 @@ namespace cxxopts
const T&
as() const
{
if (m_value == nullptr) {
throw std::domain_error("No value");
}

#ifdef CXXOPTS_NO_RTTI
return static_cast<const values::standard_value<T>&>(*m_value).get();
#else
Expand Down
3 changes: 3 additions & 0 deletions test/options.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ TEST_CASE("Basic options", "[options]")
("a,av", "a short option with a value", cxxopts::value<std::string>())
("6,six", "a short number option")
("p, space", "an option with space between short and long")
("nothing", "won't exist", cxxopts::value<std::string>())
;

Argv argv({
Expand Down Expand Up @@ -92,6 +93,8 @@ TEST_CASE("Basic options", "[options]")
CHECK(arguments[1].key() == "short");
CHECK(arguments[2].key() == "value");
CHECK(arguments[3].key() == "av");

CHECK_THROWS_AS(result["nothing"].as<std::string>(), std::domain_error);
}

TEST_CASE("Short options", "[options]")
Expand Down

0 comments on commit 84feb4b

Please sign in to comment.