Class C++;类成员模板函数,用于将对象插入到成员std::vector中

Class C++;类成员模板函数,用于将对象插入到成员std::vector中,class,templates,c++11,vector,Class,Templates,C++11,Vector,如何制作一个模板函数,将任何继承自游戏obj抽象类的类插入到已知类型的std向量中 下面是一些代码来解释它,请注意,它不应该能够编译: enum GAMEOBJ_TYPE { WIRE = 'w', GATE = 'g', }; std::vector<Wire*> wires; std::vector<Gate*> gates; template <typename T> void SortAndInsertIntoVector (T *obj,

如何制作一个模板函数,将任何继承自游戏obj抽象类的类插入到已知类型的std向量中

下面是一些代码来解释它,请注意,它不应该能够编译:

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;
  }
}
因此,在这一代中,我们将得到编译器错误,因为类型Wire不能插入到门向量中,反之亦然

有没有更好的编码方法,这样除了手动重载函数外,我还可以将obj插入到右向量中。(想象一下,如果我有20种游戏对象)

还有一种更好的优化方法,我可以在函数中不使用ENUM开关,让编译器识别哪个向量适合使用吗?(这可能是不可能的,但我听说编译时计算可以生成这样的代码)


提前谢谢

在没有模板的情况下,可能仍然使用函数调用重载,主要是因为正如您正确推断的那样:它没有在此处添加任何内容:

void SortAndInsertIntoVector (Wire* obj) {
   wires.push_back(obj);
}

void SortAndInsertIntoVector (Gates* obj) {
   gates.push_back(obj);
}
这消除了对枚举的需要,并将提供类型安全性,您可以对(我希望是有限的)数据类型使用相同的函数调用

编辑:这是一种使用模板的方法,如果您不使用名称显式命名目标向量。在下面的建议中,您始终可以通过访问存储对象,例如
gameobs::theObjects

#include <vector>
#include <iostream>

using namespace std;

template <typename T>
struct gameobjs {
    static vector<T> theObjects;
};
template <typename T>
vector<T> gameobjs<T>::theObjects;

template <typename T>
void SortAndInsertIntoVector(T* obj) {
    gameobjs<T*>::theObjects.push_back( obj );
}

int main( void ) {
    SortAndInsertIntoVector((int*)0);
    SortAndInsertIntoVector((float*)0);

    cout << "Number of ints:   " << gameobjs<int*>::theObjects.size() << endl;
    cout << "Number of floats: " << gameobjs<float*>::theObjects.size() << endl;
    cout << "Number of chars:  " << gameobjs<char*>::theObjects.size() << endl;
}

嘿,这似乎是该走的路!谢谢然而,我在尝试将变量和方法封装到类中时遇到了一个小问题。主要是因为static关键字正在分配由类类型的所有实例共享的内存。只需删除static关键字和重构即可。实际上,静态是必要的。否则,每个
gameobs::对象将引用objectpointer向量的不同实例。与原始设计相比:
导线
变量是全局变量(有原因!)。“静态”声明确保所有使用的
gameobjs::theObjects
引用相同的向量实例。
#include <vector>
#include <iostream>

using namespace std;

template <typename T>
struct gameobjs {
    static vector<T> theObjects;
};
template <typename T>
vector<T> gameobjs<T>::theObjects;

template <typename T>
void SortAndInsertIntoVector(T* obj) {
    gameobjs<T*>::theObjects.push_back( obj );
}

int main( void ) {
    SortAndInsertIntoVector((int*)0);
    SortAndInsertIntoVector((float*)0);

    cout << "Number of ints:   " << gameobjs<int*>::theObjects.size() << endl;
    cout << "Number of floats: " << gameobjs<float*>::theObjects.size() << endl;
    cout << "Number of chars:  " << gameobjs<char*>::theObjects.size() << endl;
}
Number of ints:   1
Number of floats: 1
Number of chars:  0