【问题标题】:Is it valid to use constexpr function as template argument?使用 constexpr 函数作为模板参数是否有效?
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 2015-03-10
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多