概念実証のためにこれをここに置きました。から継承する場合Updateable
: メインループから呼び出しUpdateModule::Update(delta_time);
て、構築されたクラスを更新できます。
ループされたリンク リストを使用して、更新する項目を追跡します。これにより、動的なメモリ割り当てが不要になります。UpdateModule はトリックを使用して、静的に作成されたオブジェクトでも機能することを確認します。
class Updatable
{
friend class UpdateModule;
public:
virtual void Update(float delta_time) = 0;
protected:
Updatable();
virtual ~Updatable();
private:
Updatable* m_next;
Updatable* m_prev;
};
class UpdateModule
{
friend class Updatable;
public:
static void Update(float delta_time)
{
Updatable* head = *GetHead();
Updatable* current = head;
if (current)
{
do
{
current->Update(delta_time);
current = current->m_next;
} while( current != head);
}
}
private:
static void AddUpdater(Updatable* updatable)
{
Updatable** s_head = GetHead();
if (!*s_head)
{
updatable->m_next = updatable;
updatable->m_prev = updatable;
}
else
{
(*s_head)->m_prev->m_next = updatable;
updatable->m_prev = (*s_head)->m_prev;
(*s_head)->m_prev = updatable;
updatable->m_next = (*s_head);
}
*s_head = updatable;
}
static void RemoveUpdater(Updatable* updatable)
{
Updatable** s_head = GetHead();
*s_head = updatable->m_next;
if (*s_head != updatable)
{
updatable->m_prev->m_next = updatable->m_next;
updatable->m_next->m_prev = updatable->m_prev;
}
else
{
*s_head = NULL;
}
updatable->m_next = NULL;
updatable->m_prev = NULL;
}
private:
static Updatable** GetHead()
{
static Updatable* head = NULL;
return &head;
}
};
Updatable::Updatable() : m_next(NULL), m_prev(NULL)
{
UpdateModule::AddUpdater(this);
}
Updatable::~Updatable()
{
UpdateModule::RemoveUpdater(this);
}
使用例:
class SomeClass : private Updatable
{
public:
virtual void Update(float)
{
printf("update for SomeClass was called\n");
}
};
class AnotherClass : private Updatable
{
public:
virtual void Update(float)
{
printf("update for AnotherClass was called\n");
}
};
int main()
{
SomeClass a, b;
AnotherClass c, d;
UpdateModule::Update(0);
}