设置具有非constexpr函数的constexpr变量(但可以在编译时间计算)

Set constexpr variable with non-constexpr function (but is possible to compute in compile time)

本文关键字:constexpr 编译 但可以 时间 计算 变量 函数 设置      更新时间:2023-10-16

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 %lfn", 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)

这显然不起作用。

我无法在源。CPP中的sqrt添加constexpr,因为这与Header.H中的声明不匹配。我也不能在header.h中为 sqrt添加 constexpr,因为 constexpr含义 inline,然后我需要将源中的所有内容传输到header.h。

这甚至可能吗?

no。这就是创建constexpr的原因 - 创建函数以封装编译时函数。

未完成编译时计算,编译代码的编译单元是没有意义的。

对象文件的目的是简单地连接以解决链接时间依赖关系。编译时计算必须在编译时定义,因此必须在编译时间单元中具有实现。