cast: tighten type constraints for narrow cast

This commit is contained in:
Danny Robson 2018-01-30 16:25:28 +11:00
parent 18a7790a2a
commit c9cc38eac7

View File

@ -70,15 +70,26 @@ namespace util::cast {
///////////////////////////////////////////////////////////////////////////
// cast to a smaller type and check that both values are still equal.
// cast to a smaller type of the same signedness and realness and assert
// that both values are still equal.
//
// checks will be compiled out if NDEBUG is defined.
template <typename NarrowT, typename WideT>
template <
typename NarrowT,
typename WideT,
typename = std::enable_if_t<
std::is_arithmetic_v<NarrowT> &&
std::is_arithmetic_v<WideT> &&
std::is_signed_v<NarrowT> == std::is_signed_v<WideT> &&
std::is_floating_point_v<NarrowT> == std::is_floating_point_v<WideT> &&
sizeof (NarrowT) <= sizeof (WideT),
void
>
>
constexpr NarrowT
narrow (const WideT &val)
{
static_assert (sizeof (NarrowT) <= sizeof (WideT));
static_assert (std::is_signed_v<NarrowT> == std::is_signed_v<WideT>);
#ifndef NDEBUG
auto narrow = static_cast<NarrowT> (val);