如何强制在编译时评估 constexpr 函数

How to force a constexpr function to be evaluated at compile time

给定以下代码:

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

有没有办法强制在编译时评估某些东西而不将其分配给某些 constexpr(或在编译时上下文中,如模板参数或枚举恶作剧)?

像这样:

const int a = force_compute_at_compile_time(omg());

可能是这样的(不能编译——我对 constexpr 还不太了解):

template<typename T> constexpr T force_compute_at_compile_time(constexpr const T& a) { return a; }

您可以使用非类型模板参数:

template <int N> constexpr int force_compute_at_compile_time();

const int a = force_compute_at_compile_time<omg()>();

由于 N 是一个模板参数,它 必须 是一个常量表达式。