scoped enum implementation

Discussion in 'C++' started by Jonathan Mcdougall, Feb 13, 2005.

  1. 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
    Jonathan Mcdougall, Feb 13, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. -

    enum within an enum

    -, Jun 12, 2005, in forum: Java
    Replies:
    6
    Views:
    515
  2. Jerminia
    Replies:
    3
    Views:
    606
    Roedy Green
    Oct 7, 2005
  3. Old Wolf
    Replies:
    5
    Views:
    212
    Martin Shobe
    Feb 8, 2013
  4. Replies:
    21
    Views:
    522
    Luca Risolia
    Jun 13, 2013
  5. Replies:
    3
    Views:
    263
Loading...

Share This Page