This is a pattern from Game Programming Gems 3, modified to use irrlichts containers. Tested with Visual C++ 7.1.
Code: Select all
#ifndef _T_AUTO_LIST_H_INCLUDED__
#define _T_AUTO_LIST_H_INCLUDED__
#include <irrArray.h>
//! helper enum to prevent object insertion into auto list on construction
enum E_AUTO_LIST_DO_NOT_ADD { ALT_DO_NOT_ADD };
// implementation of the autolist pattern
template< class T >
class AutoListT
{
protected:
//! special constructor prevents this from being added to list
AutoListT(E_AUTO_LIST_DO_NOT_ADD)
{
}
//! default constructor adds this to list
AutoListT()
{
T* self = static_cast<T*>(this);
append(self);
}
//! copy constructor adds this to list
AutoListT(const AutoListT&)
{
T* self = static_cast<T*>(this);
append(self);
}
//! destructor removes this from list
~AutoListT()
{
T* self = static_cast<T*>(this);
remove(self);
}
public:
/*! add an item from the auto list.
*
* if you used the special constructor, you may need to
* add the item to the auto list at a later time. this
* method is used for that.
*/
static void append(T* self)
{
irr::s32 s = List.linear_reverse_search(self);
if (s == -1)
List.push_back(self);
}
/*! remove an item from the auto list.
*
* this is useful when you don't destruct items right away,
* like when they are saved as part of a caching scheme.
*/
static void remove(T* self)
{
irr::s32 s = List.linear_reverse_search(self);
if (s != -1)
List.erase(s);
}
//! get the number of items in the list.
static irr::u32 getListSize()
{
return List.size();
}
//! get the item at the index specified.
static T* getListItem(irr::u32 n)
{
return List[n];
}
private:
static irr::core::array<T*> List;
};
/* static */
template<class T>
irr::core::array<T*> AutoListT<T>::List;
#endif // _T_AUTO_LIST_H_INCLUDED__
Code: Select all
#include "AutoListT.h"
class MyObjectType
: protected AutoListT<MyObjectType>
{
public:
MyObjectType()
{
}
virtual ~MyObjectType()
{
}
};
// somewhere in you application...
irr::u32 n;
for (n = 0; n < AutoListT<MyObjectType>::getListSize(); ++n)
{
MyObjectType* pObj = AutoListT<MyObjectType>::getListItem(n);
// do something with pObj
}