使用constexpr函数作为模板参数有效吗

Is it valid to use constexpr function as template argument?

本文关键字:参数 有效 constexpr 函数 使用      更新时间:2023-10-16
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
}

我用ideone编译了这个代码。我想知道为什么会出现编译错误。constexpr函数是否不允许作为template参数,或者它是编译器中的一个错误?

编辑:将const int get()更改为int get()此外,ideone还有一个错误,即如果删除constexpr,则仍然允许声明数组!!我认为这是C99的特点。

GCC 4.5(至少是Ideone上使用的版本(并不完全支持constexpr,包括您的有效用法;它下降到CCD_ 7。GCC 4.6及更高版本正确支持它。