I have the following code:
template<int k>
void foo()
{
}
int main(int argc, char* argv[])
{
int k = 1000;
foo<k>();
return 0;
}
which doesn’t compile, but if I declare k as const, it does:
template<int k>
void foo()
{
}
int main(int argc, char* argv[])
{
const int k = 1000;
foo<k>();
return 0;
}
Now, I see the logic behind why in the first case it doesn’t compile and in the second it does, but is this specified by the standard?
The error I’m getting is:
Error 1 error C2971: 'foo' : template parameter 'k' : 'k' : a local variable cannot be used as a non-type argument
which isn’t exactly clear, since k is a local variable also in the case it’s const… right?
§14.3.2.1 says [abridged]:
And §5.19.1 says [abridged, emphasis mine]:
Your second definition of
ksatisfies this, so it’s allowed to be used as an ICE for the template argument.The error is slightly misleading in that “a local variable cannot be used as a non-type argument” is true in general, but with certain restrictions it’s perfectly fine.