为什么 gcc5.4 不编译调用非 constexpr 函数的 constexpr 函数,而 icpc 可以编译?

Why gcc5.4 doesn't compile a constexpr function calling a non-constexpr function, but icpc does?

本文关键字:函数 编译 constexpr icpc 调用 为什么 gcc5      更新时间:2023-10-16

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——我想必须有一个使用gcc54.编译代码的选项。

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

第一个限制是关于将gcc 5.4与-std=c++11一起使用,这会因为两个return语句而产生错误。请参阅constexpr函数的主体不是return语句,因此为了解决第一个问题,您需要使用-std=c++14

然后产生

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

:10:32:错误:调用非常量表达式"int"nonstexprfunc()'

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。