How to automatically convert strongly typed enum into int?
#include <iostream>
struct a {
enum LOCAL_A { A1, A2 };
};
enum class b { B1, B2 };
int foo(int input) { return input; }
int main(void) {
std::cout << foo(a::A1) << std::endl;
std::cout << foo(static_cast<int>(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 1:
As others have said, you can't have an implicit conversion, and that's by-design.
If you want you can avoid the need to specify the underlying type in the cast.
template <typename E>
constexpr typename std::underlying_type<E>::type to_underlying(E e) noexcept {
return static_cast<typename std::underlying_type<E>::type>(e);
}
std::cout << foo(to_underlying(b::B2)) << std::endl;
Solution 2:
Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:
- 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.