Skip to content

Commit

Permalink
Merge pull request #395 from ndevenish/float
Browse files Browse the repository at this point in the history
store_into: Accept float (by accepting generic floating point)
  • Loading branch information
p-ranav authored Jan 26, 2025
2 parents 3eda91b + 1f2187b commit d924b84
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
7 changes: 4 additions & 3 deletions include/argparse/argparse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -717,12 +717,13 @@ class Argument {
return *this;
}

auto &store_into(double &var) {
template <typename T, typename std::enable_if<std::is_floating_point<T>::value>::type * = nullptr>
auto &store_into(T &var) {
if (m_default_value.has_value()) {
var = std::any_cast<double>(m_default_value);
var = std::any_cast<T>(m_default_value);
}
action([&var](const auto &s) {
var = details::parse_number<double, details::chars_format::general>()(s);
var = details::parse_number<T, details::chars_format::general>()(s);
return var;
});
return *this;
Expand Down
32 changes: 32 additions & 0 deletions test/test_store_into.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,38 @@ TEST_CASE("Test store_into(double), default value, specified" *
REQUIRE(res == 5.5);
}

// Float cases

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

program.parse_args({"./test.exe"});
REQUIRE(res == -1.0f);
}

TEST_CASE("Test store_into(float), default value, non specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");
float res = -1.0f;
program.add_argument("--float-opt").default_value(3.5f).store_into(res);

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

TEST_CASE("Test store_into(float), default value, specified" *
test_suite("store_into")) {
argparse::ArgumentParser program("test");
float res = -1.0f;
program.add_argument("--float-opt").default_value(3.5f).store_into(res);

program.parse_args({"./test.exe", "--float-opt", "5.5"});
REQUIRE(res == 5.5f);
}

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

0 comments on commit d924b84

Please sign in to comment.