2

gcc5.4 不编译以下代码:

// source.cpp
int nonconstexprfunc()
{
    return 14;
}

constexpr int func(int n)
{
    if (n < 0)
        return nonconstexprfunc();
    return n*n;
}

int main()
{
    constexpr int t1 = func(0);
    return 0;
}

我使用的命令:

$ g++ -std=c++14 -c source.cpp

输出:

In function ‘constexpr int func(int)’:
error: ‘constexpr int func(int)’ called in a constant expression
constexpr int t1 = func(0);
In function ‘int main()’:
error: ‘constexpr int func(int)’ called in a constant expression
constexpr int t1 = func(0);

但我可以使用 gcc6.4 编译那个 source.cpp。gcc5.4 不完全支持 constexpr 函数吗?

更有趣的是,我可以使用使用 gcc5.4 的 icpc(英特尔 C++ 编译器)编译该 source.cpp - 我想必须有一个选项可以使用 gcc5.4 编译该代码。

$  icpc -v
icpc version 19.0 (gcc version 5.4.0 compatibility)
$  icpc -std=c++14 -c source.cpp
no errors
4

1 回答 1

2

第一个限制是关于使用 gcc 5.4 和 -std=c++11 会产生错误,因为两个 return 语句请参阅The body of constexpr function not a return-statement所以为了解除您需要使用的第一个问题-std=c++14

然后它产生

'#1 with x86-64 gcc 5.4:在函数'constexpr int func(int)'中:

:10:32: 错误: 调用非 constexpr 函数'int nonconstexprfunc()'

     return nonconstexprfunc();        ^

:在函数'int main()'中:

:16:28: 错误:在常量表达式中调用了“constexpr int func(int)”

 constexpr int t1 = func(0);

                         Compiler returned: 1

产生的下一个错误似乎是已知的 GCC 错误(对 c++14 的误解)请参阅
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86678
https://gcc.gnu.org/bugzilla /show_bug.cgi?id=67026

您还可以查看在某些情况下允许从 constexpr 调用非 constexpr 函数

但是从它产生的错误来看:

这样做似乎很明显

constexpr int nonconstexprfunc()
{
    return 14;
}

将解决错误,并且在您的情况下会更有效率。
例如,检查与https://www.godbolt.org/添加 constexpr 或不使用 gcc 8.2 的区别。

于 2019-01-23T12:27:55.980 回答