Type-casting enum to integer and vice versa [closed]

百般思念 提交于 2020-07-05 08:04:06

问题


I have an enum

enum MYENUM
{
  VAL_1 = 0,
  VAL_2,
  VAL_3
};

and two functions that have integer and enum as parameters respectively

void MyIntegerFunction(int integerValue)
{
...
}

void MyEnumFUnction(MYENUM enumValue)
{
...
}

I have two variables

int intVar = 10;
MYENUM enumVar = VAL_2;

In which of the two cases below is it correct to do a typecasting while calling these functions and why?

Case#1. MyEnumFUnction(static_cast<MYENUM>(intVar));
Case#2. MyIntegerFunction(static_cast<int>(enumVar));

PS: No C++11


回答1:


enum to int is unambiguous cast (assuming C++ 03 where enum is basically an int), will be performed implicitly no problem. int to enum is potentially errorneous as it's a narrowing cast, not every int value is a valid enum value. That's why casting int to enum is only possible explicitly.

Same holds for C++ 11 and later standards, with the exception that C++ 11 introduced strongly typed enums and specific size enums.
Strongly typed enum is declared enum class instead of just enum, and it cannot be converted to an integer nor any other type, save for a user-defined conversion operator or function, or brute force (static_cast). Sized enums are declared like this: enum Colors : char {...}. This particular enum's values will have char type instead of the default int.



来源:https://stackoverflow.com/questions/20762509/type-casting-enum-to-integer-and-vice-versa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!