c++ - How to index all the derived components in a base component list in Entity -
i trying entity component system design simulation. here confuses me now. trying make entity class
entity.h class entity { public: entity(); virtual ~entity() = 0; //---------------------methods---------------------// void addcomponent(const shared_ptr<component> component); template<class t> t* getcomponent() const; //---------------------members---------------------// vector<shared_ptr<component>> m_components; } entity.cpp template<typename t> t* entity::getcomponent() const { component::component_type_t typeindex = /*t::component_type*/ t* returnptr = dynamic_pointer_cast<t>(m_components[component_type].get()); return returnptr; }
and component class looks this
class component { public: component(); virtual ~component() = 0; //---------------------methods---------------------// //---------------------members---------------------// typedef enum component_type_t { mesh_t, rigidbody_t, transform_t, num_types }; component_type_t componenttype; };
they way want use getcomponent()
same in unity3d
transform* t = getcomponent<transform>()
but can see cannot find way yet. way used was
class entity { ..... component* getcomponent(component::component_type_t componenttype) const { return m_components[component_type].get() }; }
and use as
transform* t = dynamic_pointer_cast<transform>(getcomponent(component::component_type_t::transform_t));
clearly tedious.
so question can use form this?
class entity { ..... template<class t> t* getcomponent() const { component::component_type_t typeindex = /*t::component_type*/ t* returnptr = dynamic_pointer_cast<t>(m_components[component_type].get()); return returnptr; }; }
i feel cleanness , speed keep using std::vector<>
storing component pointers, valid design?
did similar long time ago. think doing hard way. can modify code below suit need. components
inherited. can remove inheritance , replace class inside class or component classes inside component
class.
#include <iostream> struct vector3 { float x, y, z; vector3(float x, float y){} vector3(float x, float y,float z){} }; template <class t> class component { public: t t; void adnewcomponent(){ } }; class mesh{ public: mesh(){} }; class rigidbody{ public: rigidbody(){} void addforce(float x,float y, float z){} void addforce(vector3 force){} }; class transform{ public: transform(){} }; class object{ }; class gameobject:object, component<mesh>, component<rigidbody>, component<transform> { public: template <class t> t &getcomponent() { return this->component<t>::t; } template <class t> t &addcomponent(){ this->component<t>::adnewcomponent(); return this->component<t>::t; } }; int _tmain(int argc, _tchar* argv[]) { gameobject gameobject; gameobject.addcomponent<rigidbody>(); rigidbody rigidbody = gameobject.getcomponent<rigidbody>(); rigidbody.addforce(9,0,0); std::cin.get(); return 0; }