Check if Given Type is Scoped Enum in C++23

Check if Given Type is Scoped Enum in C++23

Scoped enumerations, also known as strongly typed enumerations (enum class) provides type safety and eliminates many of the issues associated with traditional unscoped enumerations. Unlike old-style enums, scoped enums do not implicitly convert to integral types and keep their enumerator names within their own scope. In generic programming and template-based code, it is often necessary to determine whether a type is an enumeration, and more specifically, whether it is a scoped enumeration. While std::is_enum_v has been available for a long time, it does not distinguish between scoped and unscoped enums.

Consider the following example:

#include <iostream>

enum OldStyle { A, B };

enum class NewStyle { C, D };

int main() {
    std::cout << std::is_enum_v<OldStyle> << std::endl; // 1
    std::cout << std::is_enum_v<NewStyle> << std::endl; // 1

    return 0;
}

Both OldStyle and NewStyle are recognized as enumeration types. The trait std::is_enum_v simply checks whether a type is an enum, without considering its scope.

Since C++23, the trait std::is_scoped_enum_v can be used. This makes it possible to detect specifically whether a type is a scoped enumeration.

#include <iostream>

enum OldStyle { A, B };

enum class NewStyle { C, D };

int main() {
    std::cout << std::is_scoped_enum_v<OldStyle> << std::endl; // 0
    std::cout << std::is_scoped_enum_v<NewStyle> << std::endl; // 1

    return 0;
}

Leave a Comment

Cancel reply

Your email address will not be published.