如何强制constexpr函数在编译时求值

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

本文关键字:编译 何强制 constexpr 函数      更新时间:2023-10-16

给定以下代码:

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是模板参数,因此必须是常量表达式