C++: Replacing Long Switch() Statement with Indexed Array? -
to create game object dynamically, take objecttypeid, unsigned int, , let compare within long switch() statement. if appropriate swith case found, create object , store it. because have 90 game objects, switch() long , growing 300 objects.
to avoid long switch() statement, , improve speed, perfect candidate taking advantage of indexed array store object types (objecttypeid increases 0 upward). is there way, how store object type within array?
i use this:
- aobjecttypesarray[objecttypeid] *pnewdynamicobject = new aobjecttypesarray[objecttypeid];
can advise me, please, how take advantage of dynamic array indexing in case, , how avoid long switch() statement? advice might differ idea, key use array indexing , remove long switch() statement.
an easier way create factories use template create factory method , store using function pointer or perhaps boost::function
or std::function
if they're available.
for example, given objects:
#include <iostream> struct gameobject { virtual ~gameobject() {} virtual void foo() const = 0; }; struct exampleobject : gameobject { void foo() const { std::cout << "exampleobject::foo\n"; } };
we can use template define generic object factory:
template <typename object> gameobject* object_factory() const { return new object(); };
define vector store function pointers factory methods:
#include <vector> typedef gameobject*(*factory_ptr)(); std::vector<factory_ptr> factories;
then add object factories using like:
int example_object_id = factories.size(); factories.push_back(&object_factory<exampleobject>);
and later create object with:
gameobject* obj = factories[example_object_id]();
here's complete example:
#include <iostream> #include <vector> template <typename baseobject> class game_object_factory { template <typename object> static baseobject* create_object() { return new object(); }; typedef baseobject*(*factory)(); std::vector<factory> factories; public: template <typename object> int register_type() { int index = factories.size(); factories.push_back(&create_object<object>); return index; } baseobject* create(int id) const { return factories[id](); } }; struct gameobject { virtual ~gameobject() {} virtual void foo() const = 0; }; struct example1 : gameobject { void foo() const { std::cout << "example1::foo\n"; } }; struct example2 : gameobject { void foo() const { std::cout << "example2::foo\n"; } }; int main() { game_object_factory<gameobject> factory; int obj1_id = factory.register_type<example1>(); int obj2_id = factory.register_type<example2>(); // should use smart pointer here simplify memory management. gameobject* obj = factory.create(obj2_id); obj->foo(); delete obj; }
Comments
Post a Comment