Commit 84feb4bd87d37f726b0b54816dd0ee097450e3ca
1 parent
c713b44d
Throw in ParseResult::as when option isn't present
Fixes #124.
Showing
3 changed files
with
8 additions
and
0 deletions
CHANGELOG.md
| @@ -20,6 +20,7 @@ options. The project adheres to semantic versioning. | @@ -20,6 +20,7 @@ options. The project adheres to semantic versioning. | ||
| 20 | * Fix version numbering in CMakeLists.txt | 20 | * Fix version numbering in CMakeLists.txt |
| 21 | * Remove unused declaration of the undefined `ParseResult::get_option`. | 21 | * Remove unused declaration of the undefined `ParseResult::get_option`. |
| 22 | * Throw on invalid option syntax when beginning with a `-`. | 22 | * Throw on invalid option syntax when beginning with a `-`. |
| 23 | +* Throw in `as` when option wasn't present. | ||
| 23 | 24 | ||
| 24 | ## 2.1.1 | 25 | ## 2.1.1 |
| 25 | 26 |
include/cxxopts.hpp
| @@ -1048,6 +1048,10 @@ namespace cxxopts | @@ -1048,6 +1048,10 @@ namespace cxxopts | ||
| 1048 | const T& | 1048 | const T& |
| 1049 | as() const | 1049 | as() const |
| 1050 | { | 1050 | { |
| 1051 | + if (m_value == nullptr) { | ||
| 1052 | + throw std::domain_error("No value"); | ||
| 1053 | + } | ||
| 1054 | + | ||
| 1051 | #ifdef CXXOPTS_NO_RTTI | 1055 | #ifdef CXXOPTS_NO_RTTI |
| 1052 | return static_cast<const values::standard_value<T>&>(*m_value).get(); | 1056 | return static_cast<const values::standard_value<T>&>(*m_value).get(); |
| 1053 | #else | 1057 | #else |
test/options.cpp
| @@ -53,6 +53,7 @@ TEST_CASE("Basic options", "[options]") | @@ -53,6 +53,7 @@ TEST_CASE("Basic options", "[options]") | ||
| 53 | ("a,av", "a short option with a value", cxxopts::value<std::string>()) | 53 | ("a,av", "a short option with a value", cxxopts::value<std::string>()) |
| 54 | ("6,six", "a short number option") | 54 | ("6,six", "a short number option") |
| 55 | ("p, space", "an option with space between short and long") | 55 | ("p, space", "an option with space between short and long") |
| 56 | + ("nothing", "won't exist", cxxopts::value<std::string>()) | ||
| 56 | ; | 57 | ; |
| 57 | 58 | ||
| 58 | Argv argv({ | 59 | Argv argv({ |
| @@ -92,6 +93,8 @@ TEST_CASE("Basic options", "[options]") | @@ -92,6 +93,8 @@ TEST_CASE("Basic options", "[options]") | ||
| 92 | CHECK(arguments[1].key() == "short"); | 93 | CHECK(arguments[1].key() == "short"); |
| 93 | CHECK(arguments[2].key() == "value"); | 94 | CHECK(arguments[2].key() == "value"); |
| 94 | CHECK(arguments[3].key() == "av"); | 95 | CHECK(arguments[3].key() == "av"); |
| 96 | + | ||
| 97 | + CHECK_THROWS_AS(result["nothing"].as<std::string>(), std::domain_error); | ||
| 95 | } | 98 | } |
| 96 | 99 | ||
| 97 | TEST_CASE("Short options", "[options]") | 100 | TEST_CASE("Short options", "[options]") |