Compiler Error C2971
Visual Studio 2010
'class' : template parameter 'param' : 'arg' : a local variable cannot be used as a non-type argument
You cannot use the name or address of a local variable as a template argument.
The following sample generates C2971:
// C2971.cpp
template <int *pi>
class Y {};
int global_var = 0;
int main() {
int local_var = 0;
Y<&local_var> aY; // C2971
// try the following line instead
// Y<&global_var> aY;
}
Simpler sample
Why make such a complex sample?
The following is much easier and produces the same compiler error:
The following is much easier and produces the same compiler error:
template <int N>
int function() {return N;}
int main()
{
int n = 5;
return function<n>(); // C2971
}
And actually I don't see much difference from this to
template <int N>
int function() {return N;}
int n = 5;
int main()
{
return function<n>(); // C2975
}
The thing is template usages require compile time constants, be it types or values, it's that easy (and logical if you imagine that the compiler most likely just creates a copy for the function for every different template usage).
The OP example just shows that addresses of local variables (stored on the stack) are not constant (which should be clear) while the addresses of global values are (well not their absolute value once the program is running, but the static offset from the program).
- 9/21/2010
- Masterxilo
- 9/21/2010
- Masterxilo