Boost logo

Boost :

From: Kimon Hoffmann (Kimon.Hoffmann_at_[hidden])
Date: 2008-04-14 07:01:54


vicente.botet wrote:
> In C++0x enuma have its own namespace.
> why not emulate this with namespace. There is a lot of enums in boost
> following this.
>
> namespace grays {
> enum type { black, dark, gray, light...};
> }
>
> The declaration of a variable is a little bit artificial, ...
> grays::type v;
>
> The enumeration follows the C++0x syntax.
> v= grays::back;
>
> When moving to C++0x you could do a replacement of grays::type and declare
> it as before
> enum type { black, dark, gray, light...};

I've always found the following CRTP quite helpful in those cases:

----------------------------------------------------------------------

template<typename Derived, typename ValueType = int>
class Enumeration {
   public:
     typedef ValueType value_type;

   public:
      value_type value() const {
       return m_Value;
     }

     friend bool operator<(Derived const& left, Derived const& right) {
       return (left.value() < right.value());
     }

     friend bool operator==(Derived const& left, Derived const& right) {
       return (left.value() == right.value());
     }

     friend bool operator!=(Derived const& left, Derived const& right) {
       return !(left == right);
     }

     friend bool operator<=(Derived const& left, Derived const& right) {
       return !(right < left);
     }

     friend bool operator>(Derived const& left, Derived const& right) {
       return (right < left);
     }

     friend bool operator>=(Derived const& left, Derived const& right) {
       return !(left < right);
     }

    protected:
     Enumeration(value_type const value)
       : m_Value(value)
     {}

   private:
     value_type m_Value;
};

----------------------------------------------------------------------

Which can the be used like this:

----------------------------------------------------------------------

struct Color : Enumeration<Color> {
   enum _Domain {
     red,
     green,
     blue
   };

   // Intentionally non-explicit
   Color(_Domain const value)
     : Enumeration<Color>(value)
   {}
};

void func(Color const color) {
   // ...
}

int main(int, char**) {
   Color myColor = Color::red;

   func(Color::blue);

   return 0;
};

----------------------------------------------------------------------

Best regards,
   Kimon




Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk