Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force constexpr to be evaluated at compile time [duplicate]

#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.

like image 840
Albert Avatar asked Dec 12 '25 19:12

Albert


1 Answers

For types that are allowed to exist as template value parameters, you can introduce a data structure like this:

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

Usage:

force<int, std::min(S::X, 0)>::value
like image 53
Travis Gockel Avatar answered Dec 14 '25 10:12

Travis Gockel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!