Created
April 24, 2018 06:43
-
-
Save afaikafk/3d7db7cd7742c097ecb5eae522734391 to your computer and use it in GitHub Desktop.
Check if an integral type could be safely cast to an enum.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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