#pragma once #include #include #include #include #include namespace NPrivate { [[noreturn]] void OnSafeCastToEnumUnexpectedValue(const std::type_info& valueTypeInfo); } // namespace NPrivate /** * Safely cast an integer value to the enum value. * @throw yexception is case of unknown enum underlying type value * * @tparam TEnum enum type */ template >> TEnum SafeCastToEnum(TInteger integerValue) { using TUnderlyingEnumType = std::underlying_type_t; std::optional value; try { value = SafeIntegerCast(integerValue); } catch (const TBadCastException&) { // SafeIntegerCast throws TBadCastException when TInteger cannot be cast // to TUnderlyingEnumType but the exception message is about integer // value cast being unsafe. // SafeCastToEnum must throw TBadCastException with its own exception // message even if integer cast fails. } if (value.has_value()) { for (TEnum enumValue : GetEnumAllValues()) { if (static_cast(enumValue) == *value) { return enumValue; } } } NPrivate::OnSafeCastToEnumUnexpectedValue(typeid(TEnum)); }