kelvSYC wrote:
Is there an efficient way to check whether an enumerator exists when
casting an integer into an enumerated value?
For example, say I have this:
enum MyEnum {
a = 1,
b = 2,
// more arbitrary constants
c = 1000
}
Is there a way to create a function that would return true if 1 was
entered, while (assuming 3 is not the value of a constant in MyEnum)
entering 3 would return false?
There is an alternative to enums that might be interesting to you.
If you boil down to what is represented by an enum, then it is easily
represented by a class. If you take this to the extreme level, then
enums are evil and you should represent all enums with a class.
class Color; // akin to enum
extern const Color & white; // different elements in the enum
extern const Color & black; // different elements in the enum
//
// operations you want to do on the enum
//
int OrdOf( const Color & );
int IsInSet( int );
inline bool operator==( const Color & b, const Color & a )
{
return &b == &a;
}
inline bool operator<( const Color & b, const Color & a )
{
return OrdOf( b ) < OrdOf( a );
}
//
// example expressions
//
int main()
{
white == black;
IsInSet( 3 );
}
//
// in a different cpp file - implementation
//
#include <set>
#include <cassert>
class Color
{
public:
int m_ord;
static std::set<int> m_set;
Color( int ord )
: m_ord( ord )
{
m_set.insert( ord );
}
};
std::set<int> Color::m_set;
int OrdOf( const Color & i_color )
{
return i_color.m_ord;
}
int IsInSet( int i_ord )
{
return Color::m_set.find( i_ord ) != Color::m_set.end();
}
namespace
{
Color g_white( 1 );
Color g_black( 2 );
Color g_xxx( 3 ); // this forces a core dump.
};
const Color & white = g_white;
const Color & black = g_black;