我有以下代码:
template<int k>
void foo()
{
}
int main(int argc, char* argv[])
{
int k = 1000;
foo<k>();
return 0;
}
它不编译,但如果我将 k
声明为 const
,它会:
template<int k>
void foo()
{
}
int main(int argc, char* argv[])
{
const int k = 1000;
foo<k>();
return 0;
}
现在,我明白了为什么在第一种情况下它不编译而在第二种情况下它编译的背后的逻辑,但这是由标准指定的吗?
我得到的错误是:
Error 1 error C2971: 'foo' : template parameter 'k' : 'k' : a local variable cannot be used as a non-type argument
这不是很清楚,因为 k
在 const
的情况下也是一个局部变量...对吗?
最佳答案
根据标准 14.3.2,这必须是常量表达式:
A template-argument for a non-type, non-template template-parameter shall be one of:
— an integral constant-expression of integral or enumeration type; or
— the name of a non-type template-parameter; or
— the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or
— a pointer to member expressed as described in 5.3.1 .
GCC 4.6.2 给出了一个更容易理解的错误:
error: ‘k’ cannot appear in a constant-expression
关于c++ - 模板编译错误 - 标准与否?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8232493/