简体   繁体   中英

Is there an alternative to using static_cast<int> all the time?

I have an enumeration called StackID , and throughout my code I have to static_cast it to int quite a bit - eg

StackID somestack;
int id = static_cast<int>(somestack);

Is there a shorthand alternative to doing this cast over and over again ? I have heard of "implicit" conversions - is that something I can use here?

(Possibly related to this question )

Is there something you should use instead? Probably not. If you're doing enum casts to int I would question if you're using enums properly (or if you're having to interface with a legacy API.) That being said you don't have to static_cast enums to ints. That'll happen naturally.

See this article from MSN on enums and enum->int and int->enum (where you do have to use a static_cast.)

Is there a shorthand alternative to doing this cast over and over again ?

Well, wouldn't you know., it's your lucky day! Because, yes, there is a simpler way:

int id = somestack;

Any enum value is implicitly convertible into an int .

Anyway, from your two questions regarding this issue, I'll join the concerned voices asking whether an enum is really what you want here. (I'm not saying it's wring, I know too little about your problem to know that. But from what I know it seems questionable.)

Enum values will start from zero by default and keep on increasing. Basically, enum constants themselves are integer constants. No need of typecasting them to int explicitly. When we want to represent multiple constants like error codes with unique values, instead of #define statements, we can make use of Enum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM