c++ - 使用 constexpr 函数作为模板参数是否有效?

标签 c++ templates c++11 compiler-errors constexpr

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 的一个特性。

最佳答案

GCC 4.5(至少是 Ideone 使用的版本)不完全支持 constexpr,包括您的有效用法;它变成了 const。 GCC 4.6 及更高版本正确支持它。

关于c++ - 使用 constexpr 函数作为模板参数是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6354386/

相关文章:

c++ - 如何在与C++连接的sql中插入数组元素?

c++ - 在类成员内 move 右值

c++ - 对象有不同的函数成员还是共享它们?

templates - 将 Drupal 7 中的 front.tpl 用于另一个页面

c++ - 任意 double 容器的模板语法是什么?

c++ - 错误 C2280 : attempting to reference a deleted function (atomic<int>)

c++11 中 boost::filesystem::copy_file() 缺少符号

c++ - shared_ptr 别名构造函数

c++ - 在 C++ 中获得准确的执行时间(微秒)

c++ - 声明模板的共享指针