mirror of
https://github.com/microsoft/GSL.git
synced 2024-11-03 17:56:43 -05:00
Refactor narrow
- simplify & move is_same_signedness
into function, remove uneeded detail
namespace. Merge 2 if
's with a ||
.
This commit is contained in:
parent
1999b48a51
commit
1e5f44d3ea
@ -100,15 +100,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
|
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
|
||||||
template <class T, class U>
|
template <class T, class U>
|
||||||
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
|
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
|
||||||
@ -118,10 +109,17 @@ constexpr
|
|||||||
#endif
|
#endif
|
||||||
T narrow(U u) noexcept(false)
|
T narrow(U u) noexcept(false)
|
||||||
{
|
{
|
||||||
T t = narrow_cast<T>(u);
|
constexpr const bool is_same_signedness = std::is_signed<T>::value == std::is_signed<U>::value;
|
||||||
if (static_cast<U>(t) != u) throw narrowing_error{};
|
|
||||||
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
|
const T t = narrow_cast<T>(u);
|
||||||
|
|
||||||
|
if (static_cast<U>(t) != u
|
||||||
|
|| (!is_same_signedness
|
||||||
|
&& ((t < T{}) != (u < U{}))))
|
||||||
|
{
|
||||||
throw narrowing_error{};
|
throw narrowing_error{};
|
||||||
|
}
|
||||||
|
|
||||||
return t;
|
return t;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user