Boost logo

Boost :

From: iain.denniston_at_[hidden]
Date: 2007-06-10 07:40:04


Hi all,

I wondered if anyone was interested is this idea - it's something I make a
lot of use of, so figured it may be useful to others. I'm far from being
expert on boost, the STL, or even C++ so it could easily be that this idea
is encapsulated elsewhere and I've simply missed it - apologies if this is
the case.

Also I'm new to the whole contributing to boost thing, so I hope I've not
done anything wrong in that respect.

Description

A class not dissimilar in operation to std::bitset, but specifically for
enumeration flags/bitsets (i.e. combinations of enumerations - of a single
enum type - or'd together). That is, a simple wrapper class around
enumeration based flags - expected to be completely compiled out by any
reasonable C++ compiler.

Type safety for enumeration bitsets if you like.

Motivation

The goal is simple, push potential errors from run time, back to compile
time. Additionally it should provide better self documenting code, and
assist library users in understanding the arguments required and accepted by
a function using the code.

Take an example from the STL:

void fstream::open(const char *_Filename, ios_base::openmode _Mode);

which essentially translates to:

void fstream::open(const char *_Filename, int _Mode);

Meaning that the following code will compile:

std::fstream strm;

strm.open("file.txt", 666);

Although the results will be anybody's guess - and more importantly may
change if the library is changed, producing potentially horrid bugs (not
something I would relish tracking down). The above example may be somewhat
convoluted, but many times I've seen code where flags have been required as
an argument, supposed to be from a specific enumeration only for users to
use an enumeration of a different kind, or where a flag is required, but a
user passes '0' which is not always a valid option.

The new class would mean changing the above to:

void fstream::open(const char *_Filename, boost::flags<openmode_enum>
_Mode);

which would result in an error for the given example (since "666" is not a
valid openmode_enum enumeration). Any combination of or'd openmode_enums
would, however, compile properly (and would behave as if the flags class did
not exist).

Obviously this is not a full proof solution - it's as easy to circumvent as
enumerations themselves, importantly however someone circumventing it has to
try - it'd be much more difficult to accidentally break.

Anyways - I hope I've gotten the idea across (and that you all like it :o)

Cheers for reading - all comments appreciated!

Iain


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