lundi 2 mars 2015

C++ class member template function to insert an obj into a member std::vector

How do I make a template function that can insert any inherited class from a game obj abstract class into a known type std vector?


Here is some code to make sense of it, note that it should not be able compile:



enum GAMEOBJ_TYPE {
WIRE = 'w',
GATE = 'g',
};

std::vector<Wire*> wires;
std::vector<Gate*> gates;

template <typename T>
void SortAndInsertIntoVector (T *obj, GAMEOBJ_TYPE type ) {
switch (type) {
case WIRE:
wires.push_back(obj);
break;

case GATE:
gates.push_back(obj);
break;
}
}


From what I know the compiler generates code and replaces T with the types that the compiler finds at each call to this template function to generate a function template of each type. Hence we would get 2 new functions as this:



void SortAndInsertIntoVector_CompilerMangled_Wire (Wire *obj, GAMEOBJ_TYPE type ) {
switch (type) {
case WIRE:
wires.push_back(obj);
break;

case GATE:
gates.push_back(obj);
break;
}
}

void SortAndInsertIntoVector_CompilerMangled_Gate (Gate *obj, GAMEOBJ_TYPE type ) {
switch (type) {
case WIRE:
wires.push_back(obj);
break;

case GATE:
gates.push_back(obj);
break;
}
}


Hence we would get the compiler error during this generation as the type Wire cannot be inserted into a vector of gates and vice versa.


Is there a better way to code this so that I can insert the obj into the right vector apart from manually overloading the function. (Imagine if I had 20 types of game objs)


Also is there a better optimization that I could do to not have the ENUM switch case in the function and let the compiler discern which vector is appropriate to use? (This might be impossible, but I heard of compile time computations which can generate code such as this)


Thanks in advance!


Aucun commentaire:

Enregistrer un commentaire