设置具有非constexpr函数的constexpr变量(但可以在编译时间计算)
Set constexpr variable with non-constexpr function (but is possible to compute in compile time)
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
的原因 - 创建函数以封装编译时函数。
未完成编译时计算,编译代码的编译单元是没有意义的。
对象文件的目的是简单地连接以解决链接时间依赖关系。编译时计算必须在编译时定义,因此必须在编译时间单元中具有实现。
相关文章:
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 用于循环编译的 constexpr
- 使用 constexpr 替换 #define 和 #ifdef 进行条件编译
- constexpr 使用 clang 编译 TensorFlow 时出错
- C++ constexpr语言 - 可以在编译时评估值吗?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- constexpr 函数在编译时获取值,即使我的变量不是 constexpr
- 如何判断是否在编译时计算了"constexpr"(无需手动检查)
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- Constexpr变量不是编译时值
- C++constexpr编译问题
- 模板;constexpr;编译时间
- 如果ConstexPR编译了错误分支的时间崩溃
- 使用constexpr编译时间哈希
- 仅在constexpr/编译时上下文中操作时,引用是否有用
- 使用 constexpr 编译时间字符串串联
- C++VS2015 constexpr编译错误,constexpr构造函数调用constexpr成员函数
- Constexpr编译错误使用std::acos与clang++而不是g++
- 使用constexpr编译时出错