Skip to content

Instantly share code, notes, and snippets.

@n0phx
Created April 24, 2018 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n0phx/3d7db7cd7742c097ecb5eae522734391 to your computer and use it in GitHub Desktop.
Save n0phx/3d7db7cd7742c097ecb5eae522734391 to your computer and use it in GitHub Desktop.
Check if an integral type could be safely cast to an enum.
template <typename TEnumType, TEnumType... EValues>
struct EnumCheck;
template <typename TEnumType>
struct EnumCheck<TEnumType>
{
template <typename IntegralType>
static constexpr bool is_valid(IntegralType value)
{
return false;
}
};
template <typename TEnumType, TEnumType ECurrent, TEnumType... ERest>
struct EnumCheck<TEnumType, ECurrent, ERest...>
{
using SubCheck = EnumCheck<TEnumType, ERest...>;
template <typename IntegralType>
static constexpr bool is_valid(IntegralType value)
{
return (value == static_cast<IntegralType>(ECurrent)) || SubCheck::is_valid(value);
}
};
enum class Color { red, green, blue };
using ColorCheck = EnumCheck<Color, Color::red, Color::green, Color::blue>;
int main()
{
ColorCheck::is_valid(0);
ColorCheck::is_valid(1);
ColorCheck::is_valid(2);
ColorCheck::is_valid(-2);
ColorCheck::is_valid(3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment