From 84feb4bd87d37f726b0b54816dd0ee097450e3ca Mon Sep 17 00:00:00 2001 From: Jarryd Beck Date: Mon, 19 Nov 2018 17:45:51 +1100 Subject: [PATCH] Throw in ParseResult::as when option isn't present Fixes #124. --- CHANGELOG.md | 1 + include/cxxopts.hpp | 4 ++++ test/options.cpp | 3 +++ 3 files changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb92e62..185ab21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 6fd170d..6677002 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -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&>(*m_value).get(); #else diff --git a/test/options.cpp b/test/options.cpp index 1f37172..a54be10 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -53,6 +53,7 @@ TEST_CASE("Basic options", "[options]") ("a,av", "a short option with a value", cxxopts::value()) ("6,six", "a short number option") ("p, space", "an option with space between short and long") + ("nothing", "won't exist", cxxopts::value()) ; Argv argv({ @@ -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::domain_error); } TEST_CASE("Short options", "[options]")