snippetcppCritical
How to automatically convert strongly typed enum into int?
Viewed 0 times
enumhowstronglyintconverttypedautomaticallyinto
Problem
#include
struct a {
enum LOCAL_A { A1, A2 };
};
enum class b { B1, B2 };
int foo(int input) { return input; }
int main(void) {
std::cout (b::B2)) << std::endl;
}The
a::LOCAL_A is what the strongly typed enum is trying to achieve, but there is a small difference : normal enums can be converted into integer type, while strongly typed enums can not do it without a cast.So, is there a way to convert a strongly typed enum value into an integer type without a cast? If yes, how?
Solution
Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:
Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use
If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.
- Provide type safety, thus eliminating implicit conversion to integer by integral promotion.
- Specify underlying types.
- Provide strong scoping.
Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use
static_cast to make conversion explicit.If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.
Context
Stack Overflow Q#8357240, score: 178
Revisions (0)
No revisions yet.