Limiting choices support to string type or integer type

This commit is contained in:
Pranav Srinivas Kumar 2023-10-27 10:35:04 -05:00
parent 0b8d0e2426
commit 6d49d5ee1b
2 changed files with 11 additions and 1 deletions

View File

@ -1080,7 +1080,7 @@ foo@bar:/home/dev/$ ./main fex
Invalid argument "fex" - allowed options: {foo, bar, baz} Invalid argument "fex" - allowed options: {foo, bar, baz}
``` ```
Using choices also works in integer types, e.g., Using choices also works with integer types, e.g.,
```cpp ```cpp
argparse::ArgumentParser program("test"); argparse::ArgumentParser program("test");

View File

@ -361,6 +361,15 @@ struct can_invoke_to_string {
static constexpr bool value = decltype(test<T>(0))::value; static constexpr bool value = decltype(test<T>(0))::value;
}; };
template <typename T>
struct is_choice_type_supported {
using CleanType = typename std::decay<T>::type;
static const bool value = std::is_integral<CleanType>::value ||
std::is_same<CleanType, std::string>::value ||
std::is_same<CleanType, std::string_view>::value ||
std::is_same<CleanType, const char*>::value;
};
} // namespace details } // namespace details
enum class nargs_pattern { optional, any, at_least_one }; enum class nargs_pattern { optional, any, at_least_one };
@ -546,6 +555,7 @@ public:
template <typename T> template <typename T>
void add_choice(T&& choice) { void add_choice(T&& choice) {
static_assert(details::is_choice_type_supported<T>::value, "Only string or integer type supported for choice");
static_assert(std::is_convertible_v<T, std::string_view> || details::can_invoke_to_string<T>::value, "Choice is not convertible to string_type"); static_assert(std::is_convertible_v<T, std::string_view> || details::can_invoke_to_string<T>::value, "Choice is not convertible to string_type");
if (!m_choices.has_value()) { if (!m_choices.has_value()) {
m_choices = std::vector<std::string>{}; m_choices = std::vector<std::string>{};