HOME PROJECTS SOFTWARE HARDWARE OTHER FACTS LINKS

I've built this template to provide a generic wrapper against the traditional approach for storing OR'ed combinations of values. The problem lies in the fact that there's no type checking at all. Moreover you cannot enumerate the stored values. My solution is built on basic_enum<> template and allows you to construct your flags using only allowed enums. The only restriction is that no enum value can be zero! This is to define an empty flag, otherwise the zero value would always be included in your flags (I cannot find any good reason for that but if you do let me know).

The resulting source is available here taken out of my own ocfc library.

So now how do you use my flags class? Assuming that you've already defined an my_enum class, let's define our flags in the header file as follows:

DECLARE_ENUM(my_enum, LEFT = 0, TOP = 2, RIGHT = 4, BOTTOM = 8) typedef flags<my_enum> my_flags;

Ok now let's initialise it:

my_flags __flags; __flags = _T("LEFT | BOTTOM"); // or __flags = my_enum::LEFT | my_enum::BOTTOM; // to add a flag __flags.set(my_enum::RIGHT); // and to remove it __flags.unset(my_enum::RIGHT);

Not bad isn't it but you need to test your flags as well. For instance.

if (__flags.contains(my_enum::LEFT)) { ... } if (!__flags) { // i.e. not empty ... } if (__flags.size() == 2) { // i.e. there are 2 enum values defined in our flag ... }

To iterate over each enum included in your flags simply write the following:

for (my_flags::const_iterator __i = __flags.begin(); __i != __flags.end(); ++__i) std_out << __i->str() << _T(" = ") << __i->value();

For debugging purpose I quite like to output the value of flags as a string which in the case of flags<> this is as simple as:

std_out << __flags.str();

The result of the output will be: LEFT | BOTTOM.

Valid XHTML 1.0 Strict