471,110 Members | 1,708 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,110 software developers and data experts.

scoped enum implementation

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
0 1241

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Cruinne | last post: by
11 posts views Thread by Alexander Grigoriev | last post: by
4 posts views Thread by Otto Lind | last post: by
14 posts views Thread by Vane | last post: by
6 posts views Thread by James Brown | last post: by
18 posts views Thread by Nebula | last post: by
18 posts views Thread by Visual Systems AB \(Martin Arvidsson\) | last post: by
10 posts views Thread by kar1107 | last post: by
34 posts views Thread by Steven Nagy | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.