运行函数作为 constexpr 和不作为 constexpr

Run function both as constexpr and without constexpr

本文关键字:constexpr 不作为 函数 运行      更新时间:2023-10-16

我有一个生成伪随机数的类。

我需要在 constexpr 函数中运行伪随机数生成器函数(我需要它在编译时生成它(和运行时

它运行良好,但我想知道是否有某种方法可以执行以下操作:

我想要一个生成数字的函数,我可以在编译或运行时告诉我是否想要它。 那是因为如果我写 2 个不同的代码,我必须重写相同的代码两次,这使得使用起来稍微不那么直观

我考虑过像这样使用定义:

#ifdef COMPILETIME
int constexpr function();
#else
int function();
#endif

但所有定义都是全局的。 我不能在我想通过代码时取消定义和重新定义它们

有没有办法实现这一点,或者我是否永远注定要使用 2 个单独的功能?

constexpr函数可以在编译时和运行时调用。根据调用函数的上下文,将相应地对其进行计算。例如:

constexpr int f() { return 42; }
int main()
{
int a[f()]; // array bounds must be compile time, so f is called at compile time
int b = f(); // not a constant evaluation context, so called at run-time
}

请注意,如果要在编译时计算函数,但将其存储到要在运行时更改的变量中,则可以执行以下操作:

int const x = f(); // compile time calculation
int a = x; // work done, but value of a can be changed at run-time.

如果你想要一个只能在运行时使用的函数,那么你只需要使用一个"普通"函数:

int f() { return 42; }

如果你想要一个只能在编译时使用的函数,那么你可以使用consteval函数:

consteval int f() { return 42; }