"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can Strongly Typed Enums Be Automatically Converted to Integers in C++?

Can Strongly Typed Enums Be Automatically Converted to Integers in C++?

Published on 2024-11-16
Browse:349

Can Strongly Typed Enums Be Automatically Converted to Integers in C  ?

Automating Strongly Typed Enum to Integer Conversion

In C , enums come in two flavors: strongly typed enums and regular enums. Regular enums can be implicitly converted to integers, while strongly typed enums require an explicit cast. This raises the question: is there an automated way to convert strongly typed enums to integers without resorting to explicit casts?

The answer is no, and it's intentional. Strongly typed enums are designed to prevent the implicit conversion to integers. Essentially, the compiler ensures that you explicitly acknowledge the conversion from an enumerated value to an integer.

However, there is a workaround to avoid specifying the underlying type in the cast. By utilizing a template function, we can abstract away the cast's type specification.

template 
constexpr typename std::underlying_type::type to_underlying(E e) noexcept {
    return static_cast::type>(e);
}

With this template function, the conversion can be achieved as follows:

std::cout 

This approach eliminates the explicit type specification in the cast, simplifying the conversion process while maintaining the desired behavior of enforced explicit conversion for strongly typed enums.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3