By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,819 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,819 IT Pros & Developers. It's quick & easy.

scoped enum implementation

P: n/a
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::one);
A::Test t2(t1);

t1 |= A::Test::one;

if ( t1 & A::Test::one )
;

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

if (t1 == A::Test::one)
;
}
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

Jul 23 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.