【发布时间】:2011-09-22 16:52:53
【问题描述】:
我目前有以下非模板代码:
class Vector{
public:
double data[3];
};
static Vector *myVariable;
void func() {
myVariable->data[0] = 0.;
}
int main() {
myVariable = new Vector();
func();
}
然后我想模板化维度:
template<int DIM> class Vector{
public:
double data[DIM];
};
static Vector<3>* myVariable;
void func() {
myVariable->data[0] = 0.;
}
int main() {
myVariable = new Vector<3>();
func();
}
但我最后也想用维度模板化我的变量:
template<int DIM> class Vector{
public:
double data[DIM];
};
template<int DIM> static Vector<DIM> *myVariable;
void func() {
myVariable->data[0] = 0.;
// or perform any other operation on myVariable
}
int main() {
int dim = 3;
if (dim==3)
myVariable = new Vector<3>();
else
myVariable = new Vector<4>();
func();
}
但是,最后一个版本的代码产生了一个错误:这个静态变量不能被模板化(“C2998: Vector *myVariable cannot be a template definition”)。
如果没有完全重新设计,我怎么可能纠正这个错误(比如从非模板类继承模板化 Vector 类,这将需要对虚拟方法进行更昂贵的调用,或者手动创建多个不同维度的 myVariables)?也许我只是累了,没有看到明显的答案:s
编辑:请注意,此代码是显示错误的最小工作代码,但我的实际实现模板化了完整计算几何类的维度,因此我不能只用数组替换 Vector。我发现我的问题似乎没有解决方案。
谢谢!
【问题讨论】: