我目前有以下非模板化代码:
class Vector{
public:
double data[3];
};
static Vector *myVariable;
void func() {
myVariable->data[0] = 0.;
}
int main() {
myVariable = new Vector();
func();
}
Run Code Online (Sandbox Code Playgroud)
然后我想模拟维度:
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();
}
Run Code Online (Sandbox Code Playgroud)
但我终于想要模拟我的变量,维度:
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();
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码的最后一个版本会产生错误:此静态变量无法模板化("C2998:Vector*myVariable不能是模板定义").
如果没有完全重新设计,我怎么可能纠正这个错误(比如从非模板化的类继承模板化的Vector类,这需要对虚拟方法进行更昂贵的调用,或者手动创建几个不同维度的myVariables)?也许我只是累了,没有看到明显的答案:s
编辑:请注意,此代码是显示错误的最小工作代码,但我的实际实现模板是完整计算几何类的维度,因此我不能只用数组替换Vector.我看到似乎没有解决我的问题.
谢谢!
我想我找到了!
template<int DIM> class Vector{
public:
double data[DIM];
};
static void *myVariable;
template<int DIM>
void func() {
((Vector<DIM>*)myVariable)->data[0] = 0.;
// or perform any other operation on myVariable
}
int main() {
int dim = 3;
if (dim==3)
{
myVariable = (void*) new Vector<3>();
func<3>();
}
else
{
myVariable = (void*) new Vector<4>();
func<4>();
}
}
Run Code Online (Sandbox Code Playgroud)