Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 244
BЈовић Avatar asked Dec 02 '11 13:12

BЈовић


People also ask

Can you use enum as int?

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.

Can enum be Typecasted?

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.

How do I assign an int to an enum?

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 .

Are enums strongly typed?

Enum Class C++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.


1 Answers

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; 
like image 88
R. Martinho Fernandes Avatar answered Oct 03 '22 09:10

R. Martinho Fernandes