2017-02-26 91 views
1

header.h设置constexpr变量与非constexpr函数(但是有可能在编译时计算)

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中添加constexpr作为sqrt,因为constexpr意味着inline,于是我需要将source.cpp中的所有内容都传递给header.h。

这甚至可能吗?

回答

3

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

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

目标文件是为了解决链接时间依赖性而设计的。编译时计算必须在编译时定义,因此必须在编译时间单元中有一个实现。