From 092a8e53e41da8b71996efa32eae40ff35e5a087 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Bylica?= Date: Tue, 16 Feb 2016 14:29:55 +0100 Subject: [PATCH] narrow: Check for changed sign only if types have different signess. --- include/gsl_util.h | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/include/gsl_util.h b/include/gsl_util.h index 3769b8a..4ac6187 100644 --- a/include/gsl_util.h +++ b/include/gsl_util.h @@ -22,6 +22,7 @@ #include "gsl_assert.h" // Ensures/Expects #include #include +#include #include #ifdef _MSC_VER @@ -90,10 +91,24 @@ inline constexpr T narrow_cast(U u) noexcept struct narrowing_error : public std::exception {}; +template +struct is_same_signess +{ + static const bool value = + std::is_signed::value == std::is_signed::value; +}; + // narrow() : a checked version of narrow_cast() that throws if the cast changed the value template inline T narrow(U u) -{ T t = narrow_cast(u); if (static_cast(t) != u || (t < T{}) != (u < U{})) throw narrowing_error(); return t; } +{ + T t = narrow_cast(u); + if (static_cast(t) != u) + throw narrowing_error(); + if (!is_same_signess::value && ((t < T{}) != (u < U{}))) + throw narrowing_error(); + return t; +} // // at() - Bounds-checked way of accessing static arrays, std::array, std::vector