使用 std::acos 和 clang++ 而不是 g++ 的 Constexpr 编译错误

Constexpr compile error using std::acos with clang++ not g++

我想尝试将项目从 gcc 迁移到 clang++。我承认我的无知,我不确定为什么下面的代码

template <typename T>
constexpr T pi{std::acos(T(-1.0))};

使用 g++ 静默编译,但 clang++ 产生错误

trig.hpp:3:13: error: constexpr variable 'pi<float>' must be initialized by a constant expression
constexpr T pi{std::acos(T(-1.0))};

我希望比我更了解它的人能启发我。

注意:已尝试使用 -std=C++14 和 C++1y。在 clang 版本 3.6.2 (tags/RELEASE_362/final) 下失败。适用于 g++ (GCC) 5.2.0。

Clang在这里是对的,我们不允许在常量表达式中使用acos

问题是 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 并且应该最终在 gcc 中得到修复。

Builtin functions 通常用于常量折叠,我们可以看到如果我们将 -fno-builtin 与 gcc 一起使用,它会禁用这种不符合要求的行为,我们将收到以下错误:

error: call to non-constexpr function 'double acos(double)'
constexpr T pi{std::acos(T(-1.0))};
                         ^