Is there a way to ensure a template parameter is an enum-class type?
I know type_traits
has std::is_enum
, but I don't want it to match regular enums, just enum_classes.
Example of the wanted effect:
enum class EnumClass {};
enum Enum {};
class Class {};
template <typename T>
void Example()
{
static_assert(/* T is EnumClass */, "`T` must be an enum class");
}
Example<EnumClass>(); // Ok
Example<Enum>(); // Error
Example<Class>(); // Error
I am using C++11, and unfortunately cannot go any higher (though I'd be curious to know the solution anyway, even if it involves newer standards).
Is it possible?
There is currently no way to detect or prevent multiple identical enum values in an enum.
1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.
Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.
You can achieve it with:
template<typename T>
using is_class_enum = std::integral_constant<
bool,
std::is_enum<T>::value && !std::is_convertible<T, int>::value>;
Here a demo.
If you prefer using SFINAE, the same can be achieved with:
template<typename T, typename _ = void>
struct is_class_enum : std::false_type {
};
template<typename T>
struct is_class_enum <
T,
typename std::enable_if<std::is_enum<T>::value &&
!std::is_convertible<T, int>::value>::type> :
public std::true_type {
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With