【发布时间】:2011-09-15 07:29:36
【问题描述】:
constexpr int get () { return 5; }
template<int N> struct Test {};
int main ()
{
int a[get()]; // ok
Test< get() > obj; // error:'int get()' cannot appear in a constant-expression
}
我有compiled this code with ideone。并且想知道为什么它会给出编译错误。
constexpr 函数不允许作为 template 参数还是编译器中的错误?
编辑:将const int get() 更改为int get()
此外,ideone 还有一个错误,如果你删除constexpr,那么still declaring an array is allowed!我认为这是 C99 的一项功能。
【问题讨论】:
-
你的编辑不正确,你做了
constexpr const get()。 -
在编辑上,这是 C99 的特性,gcc 有它作为扩展,但它不是正确的 C++,它不能移植。它被考虑包含在标准中并被拒绝,因为它会破坏类型(大小是类型的一部分)必须在编译时知道的不变性。在 C 中,这无关紧要,但在 C++ 中,您将无法将该数组用作模板的类型参数(编译时确切类型未知)——顺便说一下 gcc 中的行为,它将如果您尝试这样做,请抱怨。
标签: c++ templates c++11 compiler-errors constexpr