【问题标题】:Set constexpr variable with non-constexpr function (but is possible to compute in compile time)使用非 constexpr 函数设置 constexpr 变量(但可以在编译时计算)
【发布时间】:2017-02-26 03:26:28
【问题描述】:

header.h

extern constexpr double sqrt_of_2;
extern constexpr double sqrt_of_1_2;
double sqrt(double x);

main.cpp

#include <header.h>

int main() {
  int n;
  scanf("%d", &n);
  printf("%lf %lf\n", sqrt_of_2, sqrt(n));
  return 0;
}

source.cpp

#include <header.h>

double sqrt(double x) {
 // complex bits of math
 // huge function
 // must not be in header for speedy compilation
 // will call other small non-constexpr functions in this file
}

constexpr double sqrt_of_2 = sqrt(2.0);
constexpr double sqrt_of_1_2 = sqrt(0.5)

这显然行不通。

我无法在 source.cpp 中为 sqrt 添加 constexpr,因为这与 header.h 中的声明不匹配。我也不能在 header.h 中为sqrt 添加constexpr,因为constexpr 意味着inline,然后我需要将 source.cpp 中的所有内容传输到 header.h。

这可能吗?

【问题讨论】:

    标签: c++ constexpr


    【解决方案1】:

    没有。这就是创建 constexpr 的全部原因——创建函数来封装编译时函数。

    在没有完成编译时计算的情况下编译代码的编译单元是没有意义的。

    目标文件只是为了解决链接时依赖关系。编译时计算必须在编译时定义,因此必须在编译时单元中实现。

    【讨论】:

      猜你喜欢
      • 2014-01-08
      • 1970-01-01
      • 2020-05-11
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 2013-08-29
      相关资源
      最近更新 更多