繁体   English   中英

强制在编译时评估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期望为const int& ,则编译器很可能希望在某处也定义S::X ,即必须存在S::X的存储。

看到这里这里

有没有办法强制编译器在编译时评估我的constexpr

原因是:

最初,我们在init优先级的静态变量的早期初始化中遇到问题。 有一些struct Type<int> { static int max; }; struct Type<int> { static int max; }; ,以及一些全局static int x = Type<int>::max; 以及其他一些早期代码other_init使用了x 当我们更新GCC时,突然在other_initx == 0

我们认为可以通过使用constexpr避免此问题,以便始终在编译时对其进行评估。

唯一的其他方法是使用struct Type<int> { static constexpr int max(); }; struct Type<int> { static constexpr int max(); }; 而是让它成为一个函数。

constexpr在编译时评估。 您的问题是由于std::min不是constexpr ,所以无论输入什么,结果都不是const表达式(尤其是如果您使用std::min初始化具有静态生存期的变量,则它是动态初始化)。

最简单的解决方案可能是定义您自己的min ,类似于:

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

这将导致在编译时进行全面评估,并进行静态初始化。

对于允许作为模板值参数存在的类型,可以引入如下数据结构:

template <typename T, T K>
struct force
{
    static constexpr T value = K;
};

用法:

force<int, std::min(S::X, 0)>::value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM