【问题标题】:Force a constexpr function to be evaluated at runtime?强制在运行时评估 constexpr 函数?
【发布时间】:2022-08-17 19:54:12
【问题描述】:

考虑以下场景:

template <bool expensive>
constexpr auto computeValue() {
  // ...
}

void funcA() {
  static constexpr auto value_a = computeValue<false>();  // should be at compile time
  // ...
}

void funcB() {
  static const auto value_b = computeValue<true>();  // should be at runtime
  // ...
}

在我的场景中,computeValue&lt;true&gt; 是一项昂贵的计算,并且由于我的系统上的内存不足错误而无法在编译时进行评估。但是,它能够在运行时以可接受的时间量在同一台计算机上运行。 computeValue&lt;false&gt; 没有这个问题,这就是为什么它是在编译时在funcA 中计算的。

问题是编译器仍然试图在编译时评估computeValue&lt;true&gt;(),尽管我忽略了constexpr,随后内存不足。有没有办法强制它离开这个计算进行运行时评估?

  • 也许完全不相关,但你不能在运行时评估表达式一次并硬编码源中的值吗?

标签: c++ c++20 constexpr


【解决方案1】:

我能想到的唯一解决方案是制作该函数的第二个副本,除非没有constexpr

template <bool expensive>
constexpr auto computeValue() {
  // ...
}

template <bool expensive>
auto computeValueRuntime() {
  return computeValue<expensive>();
}

void funcB() {
  static const auto value_b = computeValueRuntime<true>();  // should be (and is) at runtime
  // ...
}

不过,这似乎很不优雅,所以我想知道是否有一些语法方法可以做到这一点。

【讨论】:

  • 不。这并不意味着 computeValue 正在运行时运行,即使 computeValueRuntime 正在运行。这充其量是误导。
猜你喜欢
  • 1970-01-01
  • 2012-12-24
  • 2015-08-02
  • 2017-05-26
  • 1970-01-01
  • 2021-02-13
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多