diff --git a/src/argparse.hpp b/src/argparse.hpp index cfb3f73..9833363 100644 --- a/src/argparse.hpp +++ b/src/argparse.hpp @@ -42,6 +42,7 @@ struct Argument { std::vector mNames; std::string mHelp; std::any mDefaultValue; + std::any mImplicitValue; std::function mAction; std::vector mValues; std::vector mRawValues; @@ -67,6 +68,11 @@ struct Argument { return *this; } + Argument& implicit_value(std::any aImplicitValue) { + mImplicitValue = aImplicitValue; + return *this; + } + Argument& action(std::function aAction) { mAction = aAction; return *this; @@ -176,8 +182,20 @@ class ArgumentParser { auto tCurrentArgument = argv[i]; std::map>::iterator tIterator = mArgumentMap.find(argv[i]); if (tIterator != mArgumentMap.end()) { + // Start parsing optional argument auto tArgument = tIterator->second; auto tCount = tArgument->mNumArgs; + + // Check to see if implicit value should be used + // Two cases to handle here: + // (1) User has explicitly programmed nargs to be 0 + // (2) User has left nargs to be default, i.e., 1 and provided an implicit value + if (tCount == 0 || (tArgument->mImplicitValue.has_value() && tCount == 1)) { + // Use implicit value for this optional argument + tArgument->mValues.push_back(tArgument->mImplicitValue); + tArgument->mRawValues.push_back(""); + tCount = 0; + } while (tCount > 0) { i = i + 1; if (i < argc) { diff --git a/tests/main.cpp b/tests/main.cpp index 06e37bd..fe5a6d9 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -4,3 +4,4 @@ #include #include #include +#include \ No newline at end of file diff --git a/tests/test_implicit_values.hpp b/tests/test_implicit_values.hpp new file mode 100644 index 0000000..a83ad80 --- /dev/null +++ b/tests/test_implicit_values.hpp @@ -0,0 +1,27 @@ +#pragma once +#include +#include + +TEST_CASE("Parse toggle arguments with default value", "[parse_args]") { + argparse::ArgumentParser program("test"); + program.add_argument("--verbose", "-v") + .default_value(false) + .implicit_value(true); + + program.parse_args({ "./test.exe" }); + auto arguments = program.get_arguments(); + REQUIRE(arguments.size() == 2); + REQUIRE(program.get("--verbose") == false); +} + +TEST_CASE("Parse toggle arguments with implicit value", "[parse_args]") { + argparse::ArgumentParser program("test"); + program.add_argument("--verbose") + .default_value(false) + .implicit_value(true); + + program.parse_args({ "./test.exe", "--verbose" }); + auto arguments = program.get_arguments(); + REQUIRE(arguments.size() == 1); + REQUIRE(program.get("--verbose") == true); +} \ No newline at end of file