C++ Check If Type Is Enum Class

4 min read Jul 01, 2024
C++ Check If Type Is Enum Class

Checking if a Type is an Enum Class in C++

In C++, you can use the std::is_enum trait to determine if a type is an enumeration. However, this trait does not distinguish between traditional enums and enum classes.

To specifically check if a type is an enum class, you can leverage the following approaches:

Using std::is_enum and std::is_class:

The combination of std::is_enum and std::is_class traits can help identify enum classes:

#include 

template 
constexpr bool is_enum_class() {
  return std::is_enum::value && std::is_class::value;
}

This function checks if the type T is an enumeration (std::is_enum) and also if it is a class (std::is_class). Only enum classes satisfy both conditions.

Using std::underlying_type:

The std::underlying_type trait reveals the underlying integer type of an enum. You can use it to distinguish between enum classes and traditional enums:

#include 

template 
constexpr bool is_enum_class() {
  return std::is_enum::value && !std::is_same>::value;
}

This function checks if the type T is an enumeration. If it is, it then compares the type T with the underlying integer type returned by std::underlying_type_t<T>. If they are not the same, it indicates that T is an enum class.

Using decltype and std::is_same:

You can utilize decltype and std::is_same to check if the type is an enum class:

#include 

template 
constexpr bool is_enum_class() {
  return std::is_enum::value &&
         !std::is_same(0))>::value;
}

This function checks if the type T is an enumeration. If it is, it then compares the type T with the type returned by decltype(static_cast<T>(0)). This expression casts 0 to the type T, which results in an integer value for traditional enums but a distinct type for enum classes.

Example:

#include 
#include 

enum class Color { RED, GREEN, BLUE };
enum ColorCode { RED, GREEN, BLUE };

int main() {
  std::cout << "Color is enum class: " << is_enum_class() << std::endl;
  std::cout << "ColorCode is enum class: " << is_enum_class() << std::endl;
  return 0;
}

This code will output:

Color is enum class: 1
ColorCode is enum class: 0

This demonstrates that Color is an enum class and ColorCode is a traditional enum.

Conclusion:

These approaches effectively allow you to determine if a type in C++ is an enum class. Choose the method that best suits your needs and coding style. Remember that using std::is_enum alone will not distinguish between enum classes and traditional enums.