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
700 views
in Technique[技术] by (71.8m points)

c++ - Force constexpr to be evaluated at compile time

#include <algorithm>

struct S
{
    static constexpr int X = 10;
};

int main()
{
    return std::min(S::X, 0);
};

If std::min expects a const int&, the compiler very likely would like to have the S::X also defined somewhere, i.e. the storage of S::X must exists.

See here or here.

Is there a way to force the compiler to evaluate my constexpr at compile time?

The reason is:

Initially, we had a problem in early initialization of static variables in the init priority. There was some struct Type<int> { static int max; };, and some global static int x = Type<int>::max;, and some other early code other_init used that x. When we updated GCC, suddenly we had x == 0 in other_init.

We thought that we could avoid the problem by using constexpr, so that it would always evaluate it at compile time.

The only other way would be to use struct Type<int> { static constexpr int max(); }; instead, i.e. letting it be a function.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The constexpr is evaluated at compile time. Your problem is due to the fact that std::min is not a constexpr, so regardless of its input, the results are not a const expression (and in particular, if you initialize a variable with static lifetime using std::min, it is dynamic initialization).

The simplest solution is probably to define your own min, something along the lines of:

template <typename T>
constexpr T staticMin( T a, T b )
{
    return a > b ? b : a;
}

This should result in full evaluation at compile time, and static initialization.


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

...