Tuesday 15 May 2012

c++ - Using static const class instance for a switch / case -



c++ - Using static const class instance for a switch / case -

i have class acts little enum, each instance of has unique int value starts @ 0 , increments @ every new instance.

class myenumlikeclass { static int nextid = 0; static const myenumlikeclass first; static const myenumlikeclass second; const int val_; public : myenumlikeclass() : val_(nextid++) { } operator int() const { homecoming val_; } //other methods (usually getters) omitted clarity }

i trying utilize in switch case can

myenumlikeclass value; switch(value) { case myenumlikeclass::first : break; case myenumlikeclass::second : break; default : }

i getting "case value not constant expression" errors seem because compiler doesn't know values @ compile time.

is there way work?

the argument case statement must integral constant look prior c++11. easiest way utilize const int or actual enum. if you're using c++11 can utilize built-in enum class support. see scoped enumerations.

c++ switch-statement constants

No comments:

Post a Comment