[英]Set constexpr variable with non-constexpr function (but is possible to compute in compile time)
header.h header.h
extern constexpr double sqrt_of_2;
extern constexpr double sqrt_of_1_2;
double sqrt(double x);
main.cpp 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 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)
This obviously does not work. 这显然不起作用。
I can't add constexpr
for sqrt
in source.cpp because that will not match with declaration in header.h. 我无法在source.cpp中为sqrt
添加constexpr
,因为它与header.h中的声明不匹配。 I also can't add constexpr
for sqrt
in header.h because constexpr
implies inline
, I will then need to transfer everything in source.cpp to header.h. 我也无法在header.h中为sqrt
添加constexpr
,因为constexpr
意味着inline
,我将需要将source.cpp中的所有内容传输到header.h。
Is this even possible? 这甚至可能吗?
No. That's the entire point of why constexpr
was created -- to create functions to encapsulate compile-time functions. 不。这就是为什么创建constexpr
的全部要点 - 创建封装编译时函数的函数。
It doesn't make sense to compile a compilation unit of code without the compile-time calculations done. 在没有完成编译时计算的情况下编译代码编译单元是没有意义的。
Object files are meant to simply be hooked up to resolve link-time dependencies. 目标文件只是简单地连接起来以解决链接时依赖性。 Compile-time computations must be defined at compile-time, and, therefore, must have an implementation in the compile-time unit. 编译时计算必须在编译时定义,因此必须在编译时单元中具有实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.