cast: tighten type constraints for narrow cast
This commit is contained in:
parent
18a7790a2a
commit
c9cc38eac7
17
cast.hpp
17
cast.hpp
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user