scoped enum implementation

J

Jonathan Mcdougall

For use in many of my projects, I implemented an
enum with scope using a class containing an enum
with operator overloading. Wrapped in a macro, it
gives

class A
{
public:
scoped_enum(Test)
one, two, three
scoped_enum_end
};

And Test may be used like any type. Thus, I get
the scope and the type safety.

void f()
{
A::Test t1(A::Test::eek:ne);
A::Test t2(t1);

t1 |= A::Test::eek:ne;

if ( t1 & A::Test::eek:ne )
;

switch (t1)
{
case A::Test::eek:ne:
{
break;
}
}

if (t1 == A::Test::eek:ne)
;
}


Here is the implementation:

# define scoped_enum(name) \
\
class name \
{ \
public: \
enum E; \
\
private: \
E e_; \
\
public: \
name() \
{ \
} \
\
name(E e) \
:e_(e) \
{ \
} \
\
name(int i) \
:e_(E(i)) \
{ \
} \
\
name operator|=(name t2) \
{ \
e_ = E( e_ | t2.e_ ); \
return *this; \
} \
\
name operator&=(name t2) \
{ \
e_ = E( e_ & t2.e_ ); \
return *this; \
} \
\
name operator^=(name t2) \
{ \
e_ = E( e_ ^ t2.e_ ); \
return *this; \
} \
\
operator int() \
{ \
return e_; \
} \
\
public: \
\
enum E \
{


# define scoped_enum_end \
\
}; \
};


These are the problems I came up with:
1. I think declaring an enum is illegal. If it
is, I'll have to put its definition instead,
forcing the user to repeat the name in the
closing macro.

2. The closing macro is annoying. I could not
come up with anything like
scoped_enum(Test)
{
one, two, three
};

If anyone has heard of another implementation or
has any idea, I would be glad to receive them.


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top