diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 8829f31..cb427cd 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -911,12 +911,16 @@ public: } /* Getter for options with default values. + * @throws std::logic_error if parse_args() has not been previously called * @throws std::logic_error if there is no such option * @throws std::logic_error if the option has no value * @throws std::bad_any_cast if the option is not of type T */ template T get(std::string_view aArgumentName) const { + if (!mIsParsed) { + throw std::logic_error("Nothing parsed, no arguments are available."); + } return (*this)[aArgumentName].get(); } @@ -1076,6 +1080,7 @@ private: throw std::runtime_error("Unknown argument"); } } + mIsParsed = true; } /* @@ -1115,6 +1120,7 @@ private: std::string mVersion; std::string mDescription; std::string mEpilog; + bool mIsParsed = false; std::list mPositionalArguments; std::list mOptionalArguments; std::map> mArgumentMap; diff --git a/test/test_get.cpp b/test/test_get.cpp index 35d9464..db316ba 100644 --- a/test/test_get.cpp +++ b/test/test_get.cpp @@ -10,6 +10,14 @@ TEST_CASE("Getting a simple argument" * test_suite("ArgumentParser::get")) { REQUIRE(program.get("--stuff") == "./src"); } +TEST_CASE("Skipped call to parse_args" * test_suite("ArgumentParser::get")) { + argparse::ArgumentParser program("test"); + program.add_argument("stuff"); + REQUIRE_THROWS_WITH_AS(program.get("stuff"), + "Nothing parsed, no arguments are available.", + std::logic_error); +} + TEST_CASE("Missing argument" * test_suite("ArgumentParser::get")) { argparse::ArgumentParser program("test"); program.add_argument("-s", "--stuff");