Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get arguments in optional<T> with .present<T>() #68

Merged
merged 1 commit into from
Dec 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,18 @@ program.add_argument("-o", "--output")
.help("specify the output file.");
```

#### Accessing optional arguments without default values

If you do not require an optional argument to present but has no good default value for it, you can combine testing and accessing the argument as following:

```cpp
if (auto fn = program.present("-o")) {
do_something_with(*fn);
}
```

Similar to `get`, the `present` method also accepts a template argument. But rather than returning `T`, `parser.present<T>(key)` returns `std::optional<T>`, so that when the user does not provide a value to this parameter, the return value compares equal to `std::nullopt`.

### Negative Numbers

Optional arguments start with ```-```. Can ```argparse``` handle negative numbers? The answer is yes!
Expand Down
34 changes: 31 additions & 3 deletions include/argparse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -702,6 +702,23 @@ class Argument {
throw std::logic_error("No value provided");
}

/*
* Get argument value given a type.
* @pre The object has no default value.
* @returns The stored value if any, std::nullopt otherwise.
*/
template <typename T> auto present() const -> std::optional<T> {
if (mDefaultValue.has_value())
throw std::logic_error("Argument with default value always presents");

if (mValues.empty())
return std::nullopt;
else if constexpr (details::is_container_v<T>)
return any_cast_container<T>(mValues);
else
return std::any_cast<T>(mValues.front());
}

template <typename T>
static auto any_cast_container(const std::vector<std::any> &aOperand) -> T {
using ValueType = typename T::value_type;
Expand Down Expand Up @@ -811,14 +828,25 @@ class ArgumentParser {
parse_args(arguments);
}

/* Getter enabled for all template types other than std::vector and std::list
* @throws std::logic_error in case of an invalid argument name
* @throws std::logic_error in case of incompatible types
/* Getter for options with default values.
* @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 <typename T = std::string> T get(std::string_view aArgumentName) {
return (*this)[aArgumentName].get<T>();
}

/* Getter for options without default values.
* @pre The option has no default value.
* @throws std::logic_error if there is no such option
* @throws std::bad_any_cast if the option is not of type T
*/
template <typename T = std::string>
auto present(std::string_view aArgumentName) -> std::optional<T> {
return (*this)[aArgumentName].present<T>();
}

/* Indexing operator. Return a reference to an Argument object
* Used in conjuction with Argument.operator== e.g., parser["foo"] == true
* @throws std::logic_error in case of an invalid argument name
Expand Down
57 changes: 57 additions & 0 deletions test/test_parse_args.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,32 @@ TEST_CASE("Parse a string argument with default value" *
REQUIRE(program.get("--config") == "foo.yml");
}

TEST_CASE("Parse a string argument without default value" *
test_suite("parse_args")) {
argparse::ArgumentParser program("test");
program.add_argument("--config");

WHEN("no value provided") {
program.parse_args({"test"});

THEN("the option is nullopt") {
auto opt = program.present("--config");
REQUIRE_FALSE(opt);
REQUIRE(opt == std::nullopt);
}
}

WHEN("a value is provided") {
program.parse_args({"test", "--config", ""});

THEN("the option has a value") {
auto opt = program.present("--config");
REQUIRE(opt);
REQUIRE(opt->empty());
}
}
}

TEST_CASE("Parse an int argument with value" * test_suite("parse_args")) {
argparse::ArgumentParser program("test");
program.add_argument("--count")
Expand Down Expand Up @@ -103,6 +129,37 @@ TEST_CASE("Parse a vector of float arguments" * test_suite("parse_args")) {
REQUIRE(vector[4] == 5.5f);
}

TEST_CASE("Parse a vector of float without default value" *
test_suite("parse_args")) {
argparse::ArgumentParser program("test");
program.add_argument("--vector").scan<'f', float>().nargs(3);

WHEN("no value is provided") {
program.parse_args({"test"});

THEN("the option is nullopt") {
auto opt = program.present<std::vector<float>>("--vector");
REQUIRE_FALSE(opt.has_value());
REQUIRE(opt == std::nullopt);
}
}

WHEN("a value is provided") {
program.parse_args({"test", "--vector", ".3", "1.3", "6"});

THEN("the option has a value") {
auto opt = program.present<std::vector<float>>("--vector");
REQUIRE(opt.has_value());

auto &&vec = opt.value();
REQUIRE(vec.size() == 3);
REQUIRE(vec[0] == .3f);
REQUIRE(vec[1] == 1.3f);
REQUIRE(vec[2] == 6.f);
}
}
}

TEST_CASE("Parse a vector of double arguments" * test_suite("parse_args")) {
argparse::ArgumentParser program("test");
program.add_argument("--vector")
Expand Down