为什么 gcc5.4 不编译调用非 constexpr 函数的 constexpr 函数,而 icpc 可以编译?
Why gcc5.4 doesn't compile a constexpr function calling a non-constexpr function, but icpc does?
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。
相关文章:
- 跨模板化函数编译的静态变量
- 无法使用 LoadObject() 函数编译 UE4 Actor。
- 为什么在使用转换构造函数编译代码时需要 const 复制构造函数?
- 函数编译,即使它不接受整数
- 使用C 模板函数编译时间递归
- 安卓 JNI - 'raw'函数编译失败
- C++就地析构函数编译警告
- 对 TR1 使用 boost 时提升数学特殊函数编译错误
- 显式复制构造函数编译错误
- 使用SSE内部函数编译一个简单的c++程序
- 函数编译时错误
- 模板函数编译错误
- C++:使用类型名作为基的模板类调用函数编译时错误
- 将 MATLAB 函数编译成可以在 linux 终端上运行的东西,w.out MATLAB
- boost::绑定不要使用成员模板函数编译
- C++函数编译错误
- 加速模板函数编译
- 如何在C++中使用辅助函数编译以下flex文件
- 如何让g++使用move构造函数编译c++11代码
- 同时将一组函数编译为.LIB和.DLL