我不明白为什么模板参数只能用常量变量初始化。 比如,为什么以下代码不起作用:
#include <iostream>
template <class T,int dim>
class Vec
{
T _vec[dim];
int _dim;
public:
Vec () : _dim(dim) {};
~Vec () {};
// other operators and stuff
};
int main () {
int dim = 3;
Vec < int, dim> vecInt3;
}
如果我在 main 中的 dim 定义中添加一个 const,一切都很好。这是为什么?
最佳答案
整数类型参数必须是编译时常量。您必须使用整型文字或使您的变量 const
。原因是模板是在运行前实例化的,如果您以后有机会更改变量名称,程序的行为将与模板不一致。
关于C++,模板的非参数类型 : only const variables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7513059/