Files
jeanlemotan 8297b0b45f First
2024-07-02 18:06:33 +02:00

32 lines
600 B
C++

#pragma once
#include "tl/detail/prologue.h"
#include "tl/plain_crash.h"
#include "tl/type_traits.h"
namespace tl
{
namespace detail
{
template <class T, class U>
struct is_same_signedness : integral_constant<bool, is_signed<T>::value == is_signed<U>::value>
{
};
}
template <class T, class U>
T narrow(U u) noexcept
{
T t = static_cast<T>(u);
if (static_cast<U>(t) != u)
TL_PLAIN_CRASH("Narrowing error");
if (!detail::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{})))
TL_PLAIN_CRASH("Narrowing error");
return t;
}
}