I dont understand why a template parameter can be initialized only with a const variable.
As in, why doesn’t the following code work:
#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;
}
If I add a const to the definition of dim in the main, everything is fine. Why is that?
Integer types parameters must be compile-time constants. You have to either use an integer literal or make your variable
const. The reason is the template is instantiated before runtime and if there’s a chance you can later change a variable name the program will behave inconsistent with the template.