Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

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

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))};

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Clang is correct here, we are not allowed to use acos in a constant expression.

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.

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))};
                         ^

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...