2017-02-26 87 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的原因 - 創建封裝編譯時函數的函數。

編譯代碼的編譯單元沒有完成編譯時計算是沒有意義的。

目標文件是爲了解決鏈接時間依賴性而設計的。編譯時計算必須在編譯時定義,因此必須在編譯時間單元中有一個實現。