#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?
By default, the type for enum elements is int. We can set different type by adding a colon like an example below. The different types which can be set are sbyte, byte, short, ushort, uint, ulong, and long.
Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.
Use the Type Casting to Convert an Int to Enum in C# The correct syntax to use type casting is as follows. Copy YourEnum variableName = (YourEnum)yourInt; The program below shows how we can use the type casting to cast an int to enum in C#. We have cast our integer value to enum constant One .
Enum Class C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With