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

Store ints #346

Merged
merged 4 commits into from
Apr 19, 2024
Merged
Changes from 1 commit
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
Next Next commit
Add support for general integer types in store_into.
abellgithub committed Apr 17, 2024
commit d141b8d2a151d5454cedcb127c352bec93e96b56
5 changes: 3 additions & 2 deletions include/argparse/argparse.hpp
Original file line number Diff line number Diff line change
@@ -698,9 +698,10 @@ class Argument {
return *this;
}

auto &store_into(int &var) {
template <typename T, typename std::enable_if<std::is_integral<T>::value>::type * = nullptr>
auto &store_into(T &var) {
if (m_default_value.has_value()) {
var = std::any_cast<int>(m_default_value);
var = std::any_cast<T>(m_default_value);
}
action([&var](const auto &s) {
var = details::parse_number<int, details::radix_10>()(s);
36 changes: 36 additions & 0 deletions test/test_store_into.cpp
Original file line number Diff line number Diff line change
@@ -27,6 +27,8 @@ TEST_CASE("Test store_into(bool), flag specified" *
REQUIRE(flag == true);
}

// int cases

TEST_CASE("Test store_into(int), no default value, non specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");
@@ -57,6 +59,40 @@ TEST_CASE("Test store_into(int), default value, specified" *
REQUIRE(res == 5);
}

// integral cases

TEST_CASE("Test store_into(uint8_t), no default value, non specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");
uint8_t res = 55;
program.add_argument("--int-opt").store_into(res);

program.parse_args({"./test.exe"});
REQUIRE(res == 55);
}

TEST_CASE("Test store_into(uint8_t), default value, non specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");
uint8_t res = 55;
program.add_argument("--int-opt").default_value((uint8_t)3).store_into(res);

program.parse_args({"./test.exe"});
REQUIRE(res == 3);
}

TEST_CASE("Test store_into(uint8_t), default value, specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");
uint8_t res = -1;
program.add_argument("--int-opt").default_value((uint8_t)3).store_into(res);

program.parse_args({"./test.exe", "--int-opt", "5"});
REQUIRE(res == 5);
}

// Double cases

TEST_CASE("Test store_into(double), no default value, non specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");