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_into: Accept float (by accepting generic floating point) #395

Merged
merged 1 commit into from
Jan 26, 2025
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
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
Loading