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