Skip to content
This repository was archived by the owner on Apr 14, 2023. It is now read-only.

Commit 3570681

Browse files
committed
Use references for any_cast
1 parent 68abf03 commit 3570681

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

include/argparse/argparse.hpp

+7-7
Original file line numberDiff line numberDiff line change
@@ -605,11 +605,10 @@ class Argument {
605605
if constexpr (!details::IsContainer<T>) {
606606
return get<T>() == rhs;
607607
} else {
608-
using ValueType = typename T::value_type;
609608
auto lhs = get<T>();
610609
return std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs),
611610
std::end(rhs), [](const auto &lhs, const auto &rhs) {
612-
return std::any_cast<const ValueType &>(lhs) == rhs;
611+
return lhs == rhs;
613612
});
614613
}
615614
}
@@ -856,16 +855,16 @@ class Argument {
856855
* Get argument value given a type
857856
* @throws std::logic_error in case of incompatible types
858857
*/
859-
template <typename T> T get() const {
858+
template <typename T> auto get() const -> std::conditional_t<details::IsContainer<T>, T, const T&> {
860859
if (!m_values.empty()) {
861860
if constexpr (details::IsContainer<T>) {
862861
return any_cast_container<T>(m_values);
863862
} else {
864-
return std::any_cast<T>(m_values.front());
863+
return *std::any_cast<T>(&m_values.front());
865864
}
866865
}
867866
if (m_default_value.has_value()) {
868-
return std::any_cast<T>(m_default_value);
867+
return *std::any_cast<T>(&m_default_value);
869868
}
870869
if constexpr (details::IsContainer<T>) {
871870
if (!m_accepts_optional_like_value) {
@@ -901,7 +900,7 @@ class Argument {
901900
T result;
902901
std::transform(
903902
std::begin(operand), std::end(operand), std::back_inserter(result),
904-
[](const auto &value) { return std::any_cast<ValueType>(value); });
903+
[](const auto &value) { return *std::any_cast<ValueType>(&value); });
905904
return result;
906905
}
907906

@@ -1057,7 +1056,8 @@ class ArgumentParser {
10571056
* @throws std::logic_error if the option has no value
10581057
* @throws std::bad_any_cast if the option is not of type T
10591058
*/
1060-
template <typename T = std::string> T get(std::string_view arg_name) const {
1059+
template <typename T = std::string> auto get(std::string_view arg_name) const
1060+
-> std::conditional_t<details::IsContainer<T>, T, const T&> {
10611061
if (!m_is_parsed) {
10621062
throw std::logic_error("Nothing parsed, no arguments are available.");
10631063
}

0 commit comments

Comments
 (0)