强制在编译时评估constexpr [英] 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);
};
如果 std :: min
code> const int& ,编译器很可能想让 S :: X
也定义在某处,即存储 S :: X
必须存在。
是否有办法强制编译器评估我的 constexpr
在编译时?
原因是:
最初,早期初始化静态变量在init优先级。有一些 struct Type< int> {static int max; }; 和
一些全局
使用 static int x = Type< int> :: max;
other_init x
。当我们更新GCC时,突然我们在 other_init
中有 x == 0
。
我们认为我们可以通过使用 constexpr
避免这个问题,以便它总是在编译时进行评估。
唯一的另一种方法是使用 struct Type< int> {static constexpr int max(); c>
,因为
std :: min
不是 constexpr
,因此无论其输入,结果不是一个常量表达式
(特别是,如果你使用静态
初始化一个变量生命周期使用
std :: min
,它是动态初始化)。 最简单的解决方案是定义你自己的 min
b $ b如下行:
template< typename T>
constexpr T staticMin(T a,T b)
{
return a> b? b:a;
}
这将导致在编译时进行完全评估,
static初始化。
#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.
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.
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.
这篇关于强制在编译时评估constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!