I\'m having trouble with nontype(int variable) template parameter.
Why can\'t I pass a constant int variable to a function and let the function instantiate the template?
Basically, C++ has two kinds of constants:
const int a = 5;
MyTemplate foo; // OK
const int b = rand();
MyTemplate foo; // Not OK.
The first example is a compile-time constant. In C++ standard speak, it's an Integral Constant Expression (ICE). The second example is a run-time constant. It has the same C++ type (const int
) but it's not an ICE.
Your function void run(const int j)
is a run-time constant. You could even pass in user input. Therefore it's not a valid template argument.
The reason for the rule is that the compiler must generate code based on the template argument value. It can't do so if it doesn't have a compile-time constant.