Unfortunately, there is no way to guarantee that the constexpr function, even the most trivial one, will be evaluated by the compiler if absolutely necessary. That is, if it does not appear in the place where its value is required at compile time, for example, in a template. To force the compiler to evaluate at compile time, you can do the following:
constexpr int foo_implementation (int x) { return x + 1; } #define foo(x) std::integral_constant<int, foo_implementation(x)>::value
and then use foo in your code as usual
int f = foo(123);
The best part about this approach is that it guarantees a compile-time estimate, and you get a compilation error if you pass the foo runtime variable:
int a = 2; int f = foo(a);
Itโs not so nice that it requires a macro, but it seems inevitable if you want both a guaranteed estimate of compilation time and beautiful code. (I wish it were wrong, though!)
source share