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 | 20 | * Fix version numbering in CMakeLists.txt |
| 21 | 21 | * Remove unused declaration of the undefined `ParseResult::get_option`. |
| 22 | 22 | * Throw on invalid option syntax when beginning with a `-`. |
| 23 | +* Throw in `as` when option wasn't present. | |
| 23 | 24 | |
| 24 | 25 | ## 2.1.1 |
| 25 | 26 | ... | ... |
include/cxxopts.hpp
| ... | ... | @@ -1048,6 +1048,10 @@ namespace cxxopts |
| 1048 | 1048 | const T& |
| 1049 | 1049 | as() const |
| 1050 | 1050 | { |
| 1051 | + if (m_value == nullptr) { | |
| 1052 | + throw std::domain_error("No value"); | |
| 1053 | + } | |
| 1054 | + | |
| 1051 | 1055 | #ifdef CXXOPTS_NO_RTTI |
| 1052 | 1056 | return static_cast<const values::standard_value<T>&>(*m_value).get(); |
| 1053 | 1057 | #else | ... | ... |
test/options.cpp
| ... | ... | @@ -53,6 +53,7 @@ TEST_CASE("Basic options", "[options]") |
| 53 | 53 | ("a,av", "a short option with a value", cxxopts::value<std::string>()) |
| 54 | 54 | ("6,six", "a short number option") |
| 55 | 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 | 59 | Argv argv({ |
| ... | ... | @@ -92,6 +93,8 @@ TEST_CASE("Basic options", "[options]") |
| 92 | 93 | CHECK(arguments[1].key() == "short"); |
| 93 | 94 | CHECK(arguments[2].key() == "value"); |
| 94 | 95 | CHECK(arguments[3].key() == "av"); |
| 96 | + | |
| 97 | + CHECK_THROWS_AS(result["nothing"].as<std::string>(), std::domain_error); | |
| 95 | 98 | } |
| 96 | 99 | |
| 97 | 100 | TEST_CASE("Short options", "[options]") | ... | ... |