c++ - 模板编译错误 - 标准与否?

标签 c++ templates

我有以下代码:

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

这不是很清楚,因为 kconst 的情况下也是一个局部变量...对吗?

最佳答案

根据标准 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/

相关文章:

c++ - 如何将宏生成的#foo 字符串传递给模板类?

c++ - 如何将类的某些 typedef 传递给模板

c++ - 在不同的情况下对 sizeof(arr) 得到不同的答案?;

c++ - 递增if语句arduino

c++ - 使用 auto 和 decltype 从模板类中的函数返回引用

c++ - 令人困惑的模板代码

http - Golang使用 "template"包生成动态网页给客户端耗时太长

c++ - 当我尝试读取其他 dialog.ui 的空数据时,Qt c++ 读取访问冲突

c++ - 链接列表中的虚函数 - 多个返回类型(对象)

c++ - 在 Linux 上通过管道接受文件到 C++ 应用程序的最快方法