bag.h

00001 /* */
00002 /* Bag.h */
00003 /* C++ template example */
00004 /* */
00005 
00006 /* Declare a simple container template and some accessories for it. */
00007 template<class T, size_t count>
00008 class Bag
00009 {
00010 public:
00011     typedef T type;
00012 
00013     Bag();
00014     ~Bag()                              { m_count = 0; }
00015 
00016     void Add( T* item );
00017     void Remove( T* item );
00018 
00019     T**                 begin() const   { return m_array; }
00020     const T* const *    end() const     { return m_array + m_count; }
00021 
00022 private:
00023     T*      m_array[count];
00024     size_t  m_count;
00025 };
00026 
00027 /* Iterate bag members */
00028 #define Bag_foreach( Bag, instance, iterator ) \
00029 Bag::type** iterator##curr = (instance).begin();\
00030 const Bag::type* const * iterator##last = (instance).end();\
00031 Bag::type* iterator = *iterator##curr;\
00032     for( ; iterator##curr < (Bag::type**)iterator##last; iterator = *++iterator##curr )
00033 
00034 /* Add a pointer to the set */
00035 template<class T, size_t count>
00036 void Bag::Add( T* item )
00037 {
00038     if( m_count < count )
00039     {
00040          m_array[m_count++] = item;
00041     }
00042     else
00043     {
00044         /* Some sort of 'full' handler */
00045     }
00046 }
00047 
00048 /* Construct */
00049 template<class T, size_t count>
00050 Bag::Bag()
00051 { 
00052     m_count = 0; 
00053     memset(m_array,0,sizeof(m_array)); 
00054 }
00055 
00056 /* Remove an item */
00057 template<class T, size_t count>
00058 void Bag::Remove( const T* thisOne )
00059 {
00060     T** search = begin();
00061     T** last = search + m_count;
00062     while( search < last )
00063     {
00064         if( *search == thisOne )
00065         {
00066             *search = --*last;
00067             *last = NULL;
00068             --m_count;
00069             /* Search through whole bag for duplicates */
00070         }
00071     }
00072 }

Generated on Fri Jan 2 15:28:34 2009 for Squat by  doxygen 1.5.6