diff options
| author | Jordan Maples [MSFT] <49793787+JordanMaples@users.noreply.github.com> | 2020-08-05 15:16:25 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-08-05 15:16:25 -0700 |
| commit | 552eedb3908c5bae4e1bd7250c180ae83e46d2c2 (patch) | |
| tree | ae6bb2cf330c9a8ee82a24332b6ddf35a74f6297 | |
| parent | 559f8cfaaea8ba5779219a89f938b70ca7c514b1 (diff) | |
| parent | 84847041ee44e95fe8e857545f3a184cec1d9595 (diff) | |
| download | platform_external_Microsoft-GSL-552eedb3908c5bae4e1bd7250c180ae83e46d2c2.tar.gz platform_external_Microsoft-GSL-552eedb3908c5bae4e1bd7250c180ae83e46d2c2.tar.bz2 platform_external_Microsoft-GSL-552eedb3908c5bae4e1bd7250c180ae83e46d2c2.zip | |
Merge pull request #881 from robert-andrzejuk/patch-1
Refactor `narrow`.
| -rw-r--r-- | include/gsl/gsl_util | 22 |
1 files changed, 10 insertions, 12 deletions
diff --git a/include/gsl/gsl_util b/include/gsl/gsl_util index d4f5563..89fb2ee 100644 --- a/include/gsl/gsl_util +++ b/include/gsl/gsl_util @@ -90,15 +90,6 @@ struct narrowing_error : public std::exception { }; -namespace details -{ - template <class T, class U> - struct is_same_signedness - : public std::integral_constant<bool, std::is_signed<T>::value == std::is_signed<U>::value> - { - }; -} // namespace details - // narrow() : a checked version of narrow_cast() that throws if the cast changed the value template <class T, class U> GSL_SUPPRESS(type.1) // NO-FORMAT: attribute @@ -106,10 +97,17 @@ GSL_SUPPRESS(f.6) // NO-FORMAT: attribute // TODO: MSVC /analyze does not recogn constexpr T narrow(U u) noexcept(false) { - T t = narrow_cast<T>(u); - if (static_cast<U>(t) != u) throw narrowing_error{}; - if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{}))) + constexpr const bool is_different_signedness = (std::is_signed<T>::value != std::is_signed<U>::value); + + const T t = narrow_cast<T>(u); + + if (static_cast<U>(t) != u + || (is_different_signedness + && ((t < T{}) != (u < U{})))) + { throw narrowing_error{}; + } + return t; } |
