【问题标题】:Run function both as constexpr and without constexpr以 constexpr 和不带 constexpr 的形式运行函数
【发布时间】:2020-05-17 19:27:26
【问题描述】:

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

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

它工作得很好,但我想知道是否有一些方法可以做到以下几点:

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

我曾想过像这样使用定义:

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

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

有什么方法可以实现这一点,还是我永远注定要使用 2 个单独的功能?

【问题讨论】:

  • constexpr 函数既可以在编译时调用,也可以在运行时调用。所以单个函数没有问题。
  • 该死的,我不知道。非常感谢,伙计。你应该回复答案,我会打勾,让每个人都可以看到
  • 仅供参考,与consteval对比。
  • 你问的是const int randomNumber = 9的结果吗?
  • 所以 consteval 在编译时被严格评估?

标签: c++ constexpr


【解决方案1】:

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; }

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2020-12-13
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多