Tag Archives: games

simple templated bit flags class example

The inaugural post in this category is a fun little example–a simple templated bit flags class.
Sometimes, it is nice to be able to index into a bitvector with an enumeration. Take a look at this example:

// No more than size of 32 bits
enum e_item_flags
{
    _item_flags_single_use,	
    _item_flags_placed_in_world,
    _item_flags_can_be_traded,
    _item_flags_causes_effect_on_use,
    _item_flags_can_respawn,
    k_item_flags_count
};

typedef c_flags<e_item_flags, k_item_flags_count> c_item_flags; 

c_item_flags item_flags;

...  

item_flags.set( _item_flags_single_use, false );
item_flags.set( _item_flags_placed_in_world, true);
item_flags.set( _item_flags_can_be_traded, true);

if ( item_flags.test(_item_flags_can_be_traded) )
{
    // code to trade item
    ...
}

Here we have wrapped a bitvector class as a templated flags class with an enum as the template parameter, and then typedef’d it to make it a little more readable. Finally, an example of the actual usage is shown. We are pretending that we have an ‘item’ class in a game, and we have a bunch of flags that specify some properties of the item. In this case, we are going to write the code to handle trading the item, so we’ll need to test the bit specifying whether the item in question can be traded. The whole point of this little example is that we can use the enum we defined to index into the bitvector to set or test bits. Simple and sweet. What does the code for the templated flags class look like? Take a look at the code below (flags.h):

template <typename t_enum, int max_count>
class c_flags
{
public:
    c_flags<t_enum, max_count>( void );
   ~c_flags<t_enum, max_count>( void );

    void set( t_enum, bool value );
    bool test( t_enum );
    void clear( void );

private:
    c_bitvector32 bitvector;
};

template <typename t_enum, int max_count>
c_flags<t_enum, max_count>::c_flags( void )
{
    bitvector.resize( max_count );
}

template <typename t_enum, int max_count>
c_flags<t_enum, max_count>:: ~c_flags( void )
{
    clear();
}

template<typename t_enum, int max_count>
void c_flags<t_enum, max_count>::set( t_enum T, bool value )
{
    bitvector.set( T, value );
}

template<typename t_enum, int max_count>
bool c_flags<t_enum, max_count>::test( t_enum T )
{
    return bitvector.test( T );
}

template<typename t_enum, int max_count>
void c_flags<t_enum, max_count>::clear( void )
{
    bitvector.clear_all();
}

I’m not going to go over the code for the bitvector itself, but it is pretty simple and I’ve included it at the bottom of this post. One shortcoming is that it only supports 32 bits. This is easily extended, however, so I’ll leave that to you. Furthermore, it would be nice to extend the bitvector to allow serialization (reading/writing to a file.)

example code