我需要在单个向量中存储多种类型的模板类。C++一个包含多种类型的模板类的std :: vector
例如,为:
template <typename T>
class templateClass{
bool someFunction();
};
我需要将存储所有的一个载体:
templateClass<int> t1;
templateClass<char> t2;
templateClass<std::string> t3;
etc
据我知道这是不可能的,如果是会有人说怎么样?
如果无法解释如何做出如下工作?
作为解决办法,我尝试使用基本非模板类,并从中继承模板类。
class templateInterface{
virtual bool someFunction() = 0;
};
template <typename T>
class templateClass : public templateInterface{
bool someFunction();
};
我然后创建了一个矢量来存储基地“templateInterface”级:
std::vector<templateInterface> v;
templateClass<int> t;
v.push_back(t);
这将产生以下错误:
error: cannot allocate an object of abstract type 'templateInterface'
note: because the following virtual functions are pure within 'templateInterface'
note: virtual bool templateInterface::someFunction()
为了解决这个错误我在取得的功能templateInterface不是通过提供一个函数体来进行纯虚拟,而是在编译时调用该函数而不是使用overide而是在虚函数中使用body。
如:
class templateInterface{
virtual bool someFunction() {return true;}
};
template <typename T>
class templateClass : public templateInterface{
bool someFunction() {return false;}
};
std::vector<templateInterface> v;
templateClass<int> i;
v.push_back(i);
v[0].someFunction(); //This returns true, and does not use the code in the 'templateClass' function body
有什么办法来解决这个问题,这样的重写功能被使用,或者是有其他的解决方法来存储多种模板类型中的一个载体?
看看这个链接http:// stackoverflow。com/questions/5627215/how-to-make-a-vector-of-template-structs – Elior 2013-05-13 17:25:11