I'm going to implement something like the Unity3D component model for my C++ game engine. Please, review my draft of the Component
base class:
class Component
{
public:
template<class T>
static T* create(void)
{
if (Type<T>::id == 0)
Type<T>::id = ++_idCounter;
T* component = new T();
component->_id = Type<T>::id;
return component;
}
template<class T>
inline bool is(void) const
{
return Type<T>::id == _id;
}
protected:
Component(void) {}
private:
static unsigned int _idCounter;
unsigned int _id;
template<class T> struct Type { static unsigned int id; };
};
unsigned int Component::_idCounter = 0;
template<class T> unsigned int Component::Type<T>::id = 0;
It has some RTTI-like functionality, and I can use it this way:
class ComponentA: public Component {};
class ComponentB: public Component {};
...
ComponentA* a = Component::create<ComponentA>();
ComponentB* b = Component::create<ComponentB>();
std::cout << a->is<ComponentA>() << std::endl; // 1
std::cout << b->is<ComponentB>() << std::endl; // 1
std::cout << b->is<ComponentA>() << std::endl; // 0
std::cout << a->is<ComponentB>() << std::endl; // 0
And I have a question. How can I prevent any construction of any descendant of Component
outside of Component::create
?
idCounter_
. – Lstor Jun 21 '13 at 9:54