Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure template parameter is an enum class [duplicate]

Tags:

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?

like image 263
Gilad Naaman Avatar asked Oct 01 '16 14:10

Gilad Naaman


People also ask

Can enum have duplicate values C++?

There is currently no way to detect or prevent multiple identical enum values in an enum.

Can two enums have the same value?

1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

How to define enum in python?

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.

Why use enums python?

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.


1 Answers

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 {
};
like image 178
BiagioF Avatar answered Sep 26 '22 12:09

BiagioF