【发布时间】:2013-05-07 19:39:00
【问题描述】:
我需要在一个向量中存储多种类型的模板类。
例如,对于:
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 中的函数不是纯虚函数,这是编译的,但是在调用函数时不使用覆盖,而是使用虚函数中的函数体。
例如:
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
有没有办法解决这个问题,以便使用被覆盖的函数,或者是否有另一种解决方法可以将多个模板类型存储在一个向量中?
【问题讨论】: