Boost logo

Boost :

From: Daniel Frey (daniel.frey_at_[hidden])
Date: 2003-05-26 14:08:11


Today, I was actually assigned the task to create the new handling of
enums for our company's code base, so I'll think about the whole problem
anyway. We already had them packed into classes but not with base
classes for different categories (see below). I don't know yet if I can
post the stuff here (license), but it needs some time anyway...

Dave Harris wrote:

> Would there be any interest in adding specific support for enums to
> operators.hpp? Enums are used in two main idiomatic ways - as bit-flags or

I'm not sure it's a candidate for operators.hpp, but maybe I haven't
understood your intend good enough. Currently I would say it's a new
library.

> as sequential cases - and it would be good to have direct and explicit
> support for these. However, enums are not class types and cannot use the
> inheritance mechanism which the current operators.hpp relies on.
>
> What I have in mind is a syntax like:
>
> namespace Colours {
> using namespace boost::enum_types::ordinal;
> enum Type {
> red, blue, green, end
> };
> }
>
> namespace IoMode {
> using namespace boost::enum_types::bitflag;
> enum Type {
> read=0x01, write=0x02, readwrite=0x03
> };
> }

I think that namespaces are not a good solution. Classes are IMHO
better, as you can use inheritance:

class Colours : public boost::enumeration< Colours >
{
    enum type { RED, GREEN, BLUE, end };
};

class IoMode : public boost::bitflags< IoMode >
{
    enum type { READ = 0x01, WRITE = 0x02, RW = 0x03 };
};

Where the base class provides the needed operators, etc. I'd also like
to see how the preprocessor can help. This way, we can probably create
string conversion functions without repeating the identifiers, maybe
even the 0x02, 'end', etc. can be added automatically.

Besides your two categories, I think there is a third: Enums with
guaranteed value, e.g.:

class Month : public boost::values< Month >
{
    enum type { JANUARY = 1, ... };
};

But I'm not sure where the exact semantic differences are. This may be
very specific for each user.

Given that we have boost::enumeration< T > derived from some
boost::enumeration_base, we can also easily use type_traits to detect
all enums and create specializations / overloads.

A last point for classes: IMO an enum (or it's replacement) should be
defined in one place only. A namespace - by it's nature - is open for
extensions which is not required here and could only cause confusion if
people accidentially reopen the namespace and add other things. The
class will complain immediatly and is therefore safer.

Regards, Daniel

-- 
Daniel Frey
aixigo AG - financial training, research and technology
Schloß-Rahe-Straße 15, 52072 Aachen, Germany
fon: +49 (0)241 936737-42, fax: +49 (0)241 936737-99
eMail: daniel.frey_at_[hidden], web: http://www.aixigo.de

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