Changed implementation of gsl::narrow to throw gsl::narrowing_error

Implementation now behaves as described in the C++ Core Guidlines
This commit is contained in:
Nicholas Londey
2020-04-22 10:09:13 +10:00
parent 9f6a9a5807
commit 61534ca3ad
2 changed files with 9 additions and 11 deletions

View File

@ -96,6 +96,10 @@ constexpr T narrow_cast(U&& u) noexcept
return static_cast<T>(std::forward<U>(u));
}
struct narrowing_error : public std::exception
{
};
namespace details
{
template <class T, class U>
@ -115,9 +119,9 @@ constexpr
T narrow(U u) noexcept(false)
{
T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u) gsl::details::terminate();
if (static_cast<U>(t) != u) throw narrowing_error{};
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
gsl::details::terminate();
throw narrowing_error{};
return t;
}