From 2cc081928d8ece1c322c8ee0107fac64138f6125 Mon Sep 17 00:00:00 2001 From: DapengFeng Date: Tue, 29 Oct 2024 08:57:28 +0800 Subject: [PATCH 1/2] check whether the string is an arithmetic value before converting it. --- include/argparse/argparse.hpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 31b54db..2c60e5d 100755 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -40,6 +40,7 @@ #include // for declval, false_type, true_type, is_enum #include // for move, pair #include // for vector +#include // for regex, regex_match #if __has_include() #include // for enum_entries @@ -163,6 +164,12 @@ namespace argparse { explicit ConvertType(const T &value) : ConvertBase(), data(value) {}; void convert(const std::string &v) override { + if constexpr (std::is_arithmetic_v) { + // check if the string is an arithmetic value + if (!std::regex_match(v, std::regex(("((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?")))) { + throw std::invalid_argument("Invalid argument, could not convert \"" + v + "\" to " + typeid(T).name()); + } + } data = get(v); } @@ -454,7 +461,7 @@ namespace argparse { program_name = std::filesystem::path(argv[0]).stem().string(); params = std::vector(argv + 1, argv + argc); - bool& _help = flag("?,help", "print help"); + bool& _help = flag("h,help", "print help"); auto is_value = [&](const size_t &i) -> bool { return params.size() > i && (params[i][0] != '-' || (params[i].size() > 1 && std::isdigit(params[i][1]))); // check for number to not accidentally mark negative numbers as non-parameter From c7a14246b826aab78d0fc9779c9dd727e558f369 Mon Sep 17 00:00:00 2001 From: DapengFeng Date: Tue, 29 Oct 2024 09:49:08 +0800 Subject: [PATCH 2/2] fix type traits check of bool --- include/argparse/argparse.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 2c60e5d..31633e3 100755 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -164,7 +164,7 @@ namespace argparse { explicit ConvertType(const T &value) : ConvertBase(), data(value) {}; void convert(const std::string &v) override { - if constexpr (std::is_arithmetic_v) { + if constexpr (std::is_arithmetic_v && !std::is_same_v) { // check if the string is an arithmetic value if (!std::regex_match(v, std::regex(("((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?")))) { throw std::invalid_argument("Invalid argument, could not convert \"" + v + "\" to " + typeid(T).name());