Reputation: 1129
I have a class which acts a little like an enum, each instance of it has a unique int value which starts at 0 and increments at 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
{
return val_;
}
//other methods (usually getters) omitted for clarity
}
I am trying to use it in a switch case so that I can do something like
MyEnumLikeClass value;
switch(value)
{
case MyEnumLikeClass::FIRST :
break;
case MyEnumLikeClass::SECOND :
break;
default :
}
I am getting "case value is not a constant expression" errors which seem to be because the compiler doesn't know the values at compile time.
Is there any way to get this to work?
Upvotes: 0
Views: 1281
Reputation: 9770
The argument to a case
statement must be an integral constant expression prior to C++11. The easiest way to do that is to use a const int
or an actual enum
. If you're using C++11 then you can simply use the built-in enum class
support. See the scoped enumerations.
Upvotes: 2