问题描述
我想尝试将项目从 gcc 迁移到 clang++.我承认我的无知,我不知道为什么下面的代码
I want to experiment with migrating a project from gcc to clang++. I admit ignorance on my part, I'm not sure why the following bit of code
template <typename T>
constexpr T pi{std::acos(T(-1.0))};
使用 g++ 静默编译,但 clang++ 产生错误
compiles silently with g++ but clang++ produces the error
trig.hpp:3:13: error: constexpr variable 'pi<float>' must be initialized by a constant expression
constexpr T pi{std::acos(T(-1.0))};
我希望有一个比我更了解它的人能够启发我.
and I was hoping someone who knows more about it than I do could enlighten me.
注意:尝试使用 -std=C++14 和 C++1y.在 clang 版本 3.6.2 (tags/RELEASE_362/final) 下失败.适用于 g++ (GCC) 5.2.0.
NB: Tried with -std=C++14 and C++1y. Fails under clang version 3.6.2 (tags/RELEASE_362/final). Works with g++ (GCC) 5.2.0.
推荐答案
Clang 在这里是正确的,我们不允许在常量表达式中使用 acos
.
Clang is correct here, we are not allowed to use acos
in a constant expression.
问题是 acos 在标准但 gcc 将标准中未标记的一些函数包括 acos 视为 constexpr.这是一个不符合标准的扩展,最终应在 gcc 中修复.
The issue is that acos is not marked constexpr in the standard but gcc treats some functions not marked in the standard including acos as constexpr. This is a non-conforming extension and should eventually be fixed in gcc.
内置函数常用于常量折叠,我们可以看看我们是否将 -fno-builtin
与 gcc 一起使用,它会禁用这种不符合规定的行为,我们将收到以下错误:
Builtin functions are often used to constant fold and we can see if we use -fno-builtin
with gcc it disables this non-conforming behavior and we will receive the following error:
error: call to non-constexpr function 'double acos(double)'
constexpr T pi{std::acos(T(-1.0))};
^
这篇关于Constexpr 编译错误使用 std::acos 和 clang++ 而不是 g++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!