Given the following code:
constexpr int omg() { return 42; }
const int a = omg(); // NOT guaranteed to be evaluated at compile time
constexpr const int a = omg(); // guaranteed to be evaluated at compile time
Is there a way to force something to be evaluated at compile time without assigning it to something constexpr (or in a compile time context like a template parameter ot enum shenanigans)?
Something like this:
const int a = force_compute_at_compile_time(omg());
perhaps something like this (which doesn't compile - I'm not much into constexpr yet):
template<typename T> constexpr T force_compute_at_compile_time(constexpr const T& a) { return a; }
You could use non-type template arguments:
template <int N> constexpr int force_compute_at_compile_time();
const int a = force_compute_at_compile_time<omg()>();
Since N
is a template argument, it has to be a constant expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With