Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

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)

like image 325
BeeBand Avatar asked Aug 21 '10 14:08

BeeBand


People also ask

Why is static_cast better than C style cast?

static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt. Intentions are conveyed much better using C++ casts.

What is the difference between static_cast and Dynamic_cast?

static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.

What is the point of static_cast?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

Why do we need static_cast in C++?

In C++ the static_cast<>() will allow the compiler to check whether the pointer and the data are of same type or not. If not it will raise incorrect pointer assignment exception during compilation.


2 Answers

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.)

like image 59
wheaties Avatar answered Sep 21 '22 22:09

wheaties


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.)

like image 27
sbi Avatar answered Sep 18 '22 22:09

sbi