From 1e5f44d3eaf2f87df3bd0fafb61ab1bd0fadcce2 Mon Sep 17 00:00:00 2001 From: Robert Andrzejuk Date: Wed, 29 Apr 2020 20:11:44 +0200 Subject: [PATCH 1/2] Refactor `narrow` - simplify & move `is_same_signedness` into function, remove uneeded `detail` namespace. Merge 2 `if`'s with a `||`. --- include/gsl/gsl_util | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/include/gsl/gsl_util b/include/gsl/gsl_util index bc65923..cdb94ac 100644 --- a/include/gsl/gsl_util +++ b/include/gsl/gsl_util @@ -100,15 +100,6 @@ struct narrowing_error : public std::exception { }; -namespace details -{ - template - struct is_same_signedness - : public std::integral_constant::value == std::is_signed::value> - { - }; -} // namespace details - // narrow() : a checked version of narrow_cast() that throws if the cast changed the value template GSL_SUPPRESS(type.1) // NO-FORMAT: attribute @@ -118,10 +109,17 @@ constexpr #endif T narrow(U u) noexcept(false) { - T t = narrow_cast(u); - if (static_cast(t) != u) throw narrowing_error{}; - if (!details::is_same_signedness::value && ((t < T{}) != (u < U{}))) + constexpr const bool is_same_signedness = std::is_signed::value == std::is_signed::value; + + const T t = narrow_cast(u); + + if (static_cast(t) != u + || (!is_same_signedness + && ((t < T{}) != (u < U{})))) + { throw narrowing_error{}; + } + return t; } From 84847041ee44e95fe8e857545f3a184cec1d9595 Mon Sep 17 00:00:00 2001 From: Robert Andrzejuk Date: Wed, 29 Apr 2020 20:39:44 +0200 Subject: [PATCH 2/2] In `narrow` refactor `!is_same_signedness` to `is_different_signedness` --- include/gsl/gsl_util | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/gsl/gsl_util b/include/gsl/gsl_util index cdb94ac..19e4831 100644 --- a/include/gsl/gsl_util +++ b/include/gsl/gsl_util @@ -109,12 +109,12 @@ constexpr #endif T narrow(U u) noexcept(false) { - constexpr const bool is_same_signedness = std::is_signed::value == std::is_signed::value; + constexpr const bool is_different_signedness = (std::is_signed::value != std::is_signed::value); const T t = narrow_cast(u); if (static_cast(t) != u - || (!is_same_signedness + || (is_different_signedness && ((t < T{}) != (u < U{})))) { throw narrowing_error{};