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:ne);
A::Test t2(t1);
t1 |= A::Test:ne;
if ( t1 & A::Test:ne )
;
switch (t1)
{
case A::Test:ne:
{
break;
}
}
if (t1 == A::Test: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
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:ne);
A::Test t2(t1);
t1 |= A::Test:ne;
if ( t1 & A::Test:ne )
;
switch (t1)
{
case A::Test:ne:
{
break;
}
}
if (t1 == A::Test: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