--- a/src/typeconversions.h Wed Jun 22 16:13:15 2022 +0300 +++ b/src/typeconversions.h Wed Jun 22 16:53:35 2022 +0300 @@ -85,4 +85,20 @@ return reinterpret_cast<reftype>(enu); } +//! \brief A version of static_cast that only works if casting from a wider +//! integer type to a narrower integer type. +template<typename T, typename R> +constexpr auto narrow(R x) +-> std::enable_if_t<sizeof(T) <= sizeof(R) and std::is_signed_v<T> == std::is_signed_v<R>, T> +{ + return static_cast<T>(x); +} + +template<typename T, typename R> +constexpr auto widen(R x) +-> std::enable_if_t<sizeof(T) >= sizeof(R) and std::is_signed_v<T> == std::is_signed_v<R>, T> +{ + return static_cast<T>(x); +} + #endif // TYPECONVERSIONS_H